Menu
CoddyTech

HashMap 메서드

Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨. 59개 중 16번째.

HashMap은 일반적인 작업에 유용한 여러 메서드를 제공합니다. 여기 몇 가지 중요한 메서드가 있습니다:

  • isEmpty(): HashMap이 비어 있는지 확인합니다. 키-값 매핑이 없으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
  • size(): HashMap의 키-값 매핑 개수를 반환합니다.
  • clear(): HashMap에서 모든 매핑을 제거합니다. 이 호출이 반환된 후 맵은 비어 있게 됩니다.

예를 들어 먼저 HashMap을 만들어 봅시다:

HashMap<String, Integer> scores = new HashMap<>();

HashMap이 비어 있는지 확인하려면:

System.out.println(scores.isEmpty());
// 출력: true

항목을 추가하면:

scores.put("Coddy", 100);
System.out.println(scores.isEmpty());
// 출력: false

size() 메서드는 HashMap의 키-값 쌍 개수를 반환합니다.

System.out.println(scores.size());
// 출력: 1

clear() 메서드는 HashMap에서 모든 키-값 매핑을 제거합니다.

scores.clear();
System.out.println(scores.isEmpty());
// 출력: true
challenge icon

챌린지

쉬움

testHashMapMethods라는 메서드를 작성하세요. 이 메서드는 입력으로 이름이 data인 HashMap을 받습니다. 메서드는 다음 작업을 수행해야 합니다:

  1. HashMap이 비어 있는지 확인하고 다음을 출력합니다:

    Is empty: true 또는 Is empty: false

  2. 키-값 매핑의 개수를 구하고 다음을 출력합니다:

    Size: X(여기서 X는 HashMap의 크기입니다).

  3. clear()를 사용하여 HashMap에서 모든 매핑을 제거합니다.
  4. 비운 후 HashMap이 다시 비어 있는지 확인하고 다음을 출력합니다:

    Is empty after clear: true
     

직접 해보기

// --- hashmap 문자열을 hashmap으로 변환하는 모듈 ---
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
// -----------------------------
import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static void testHashMapMethods(HashMap<String, Integer> data) {
        // 여기에 코드를 작성하세요
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String hashMapString = scanner.nextLine();

        // HashMap의 String을 HashMap으로 변환
        Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
        HashMap<String, Integer> data = new Gson().fromJson(hashMapString, mapType);

        testHashMapMethods(data);
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리와 흐름의 모든 레슨

직접 연습해 보세요: 온라인 Java 컴파일러