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());
// Output: true항목을 추가하면:
scores.put("Coddy", 100);
System.out.println(scores.isEmpty());
// Output: falseHashMap의 size() 메서드는 키-값 쌍의 수를 반환합니다.
System.out.println(scores.size());
// 출력: 1clear() 메서드는 HashMap에서 모든 키-값 매핑을 제거합니다.
scores.clear();
System.out.println(scores.isEmpty());
// Output: true챌린지
쉬움testHashMapMethods라는 이름의 메서드를 생성하세요. 이 메서드는 data라는 이름의 <strong>HashMap</strong>을 입력으로 받습니다. 이 메서드는 다음 작업을 수행해야 합니다:
HashMap이 비어 있는지 확인하고 출력하세요:
Is empty: true또는Is empty: false키-값 매핑의 수를 가져오고 출력하세요:
Size: X(여기서<i>X</i>는 HashMap의 크기입니다).- HashMap에서
<strong>clear()</strong>를 사용하여 모든 매핑을 제거하세요. 지우기 후 HashMap이 다시 비어 있는지 확인하고 출력하세요:
Is empty after clear: true
치트 시트
일반적인 HashMap 유틸리티 메서드:
isEmpty(): HashMap에 키-값 매핑이 없으면true를 반환합니다size(): HashMap의 키-값 매핑 수를 반환합니다clear(): HashMap에서 모든 매핑을 제거합니다
HashMap<String, Integer> scores = new HashMap<>();
// Check if empty
System.out.println(scores.isEmpty()); // true
// Add item and check again
scores.put("Coddy", 100);
System.out.println(scores.isEmpty()); // false
// Get size
System.out.println(scores.size()); // 1
// Clear all mappings
scores.clear();
System.out.println(scores.isEmpty()); // true직접 해보기
// --- 해시맵 문자열을 해시맵으로 변환하는 모듈 ---
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 문자열을 HashMap으로 변환
Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
HashMap<String, Integer> data = new Gson().fromJson(hashMapString, mapType);
testHashMapMethods(data);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.