HashMap은 Map 인터페이스를 구현하는 클래스입니다. 해시 테이블을 기반으로 합니다. null 값과 null 키를 허용합니다.
HashMap 개체에 키-값 쌍을 저장할 수 있습니다. 그렇게 하면 각 키의 값을 검색할 수 있지만 키에 사용하는 값은 고유해야 합니다.
중복된 값
put 명령은 값을 지정된 키와 연결합니다. 즉, 키가 이미 존재하는 키-값 쌍을 추가하는 경우 이 방법은 키의 기존 값을 새 값으로 대체합니다.
예시
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class DuplicatesInHashMap {
public static void main(String args[]) {
HashMap<String, Long> map = new HashMap<String, Long>();
map.put("Krishna", 9000123456L);
map.put("Rama", 9000234567L);
map.put("Sita", 9000345678L);
map.put("Bhima", 9000456789L);
map.put("Yousuf ", 9000456789L);
System.out.println("Values Stored . . . . . .");
//Retrieving the values of a Hash map
Iterator it1 = map.entrySet().iterator();
System.out.println("Contents of the hashMap are: ");
while(it1.hasNext()){
Map.Entry <String, Long> ele = (Map.Entry) it1.next();
System.out.print(ele.getKey()+" : ");
System.out.print(ele.getValue());
System.out.println();
}
map.put("Bhima", 0000000000L);
map.put("Rama", 0000000000L);
//Retrieving the values of a Hash map
Iterator it2 = map.entrySet().iterator();
System.out.println("Contents of the hashMap after inserting new key-value pair: ");
while(it2.hasNext()){
Map.Entry <String, Long> ele = (Map.Entry) it2.next();
System.out.print(ele.getKey()+" : ");
System.out.print(ele.getValue());
System.out.println();
}
}
} 출력
Values Stored . . . . . . Contents of the hashMap are: Yousuf : 9000456789 Krishna : 9000123456 Sita : 9000345678 Rama : 9000234567 Bhima : 9000456789 Contents of the hashMap after inserting new key-value pair: Yousuf : 9000456789 Krishna : 9000123456 Sita : 9000345678 Rama : 0 Bhima : 0