Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java HashMap에 중복 키를 넣으면 어떻게 될까? put() 메서드의 동작 원리

HashMapMap 인터페이스를 구현한 대표적인 컬렉션 클래스로, 내부적으로 해시 테이블(Hash Table) 구조를 기반으로 동작합니다. HashMap은 null 키 하나와 여러 개의 null 값을 허용한다는 특징이 있습니다.

HashMap에는 키(Key)와 값(Value)으로 이루어진 데이터 쌍을 저장할 수 있으며, 저장된 키를 통해 해당 값을 빠르게 조회할 수 있습니다. 다만 키는 반드시 고유(unique)해야 하며, 같은 키가 두 번 존재할 수 없습니다.

중복 키를 추가하면 어떻게 되나?

put() 메서드는 지정된 키에 값을 연결(저장)하는 역할을 합니다. 만약 이미 존재하는 키로 다시 데이터를 저장하면, 새로운 항목이 추가되는 것이 아니라 기존 키의 값이 새로운 값으로 덮어쓰기(replace)됩니다. 즉, 중복 키는 에러 없이 조용히 기존 값을 대체하는 방식으로 처리됩니다.

예제 코드

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 . . . . . .");

        // HashMap에 저장된 값 조회
        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();
        }

        // 중복 키 "Bhima", "Rama"에 새 값 저장 → 기존 값이 덮어써짐
        map.put("Bhima", 0000000000L);
        map.put("Rama", 0000000000L);

        // 갱신 후 HashMap 값 재조회
        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

결과 분석

실행 결과를 보면 처음에는 5개의 키-값 쌍이 모두 정상적으로 저장되어 있지만, put()으로 "Bhima"와 "Rama"라는 기존에 존재하던 키에 새 값을 넣은 뒤에는 해당 키들의 값이 0(0000000000L)으로 변경된 것을 확인할 수 있습니다.

즉, Java의 HashMap에서 중복 키를 추가하면 예외가 발생하거나 새 요소가 늘어나지 않고, 해당 키에 매핑된 기존 값이 새 값으로 교체됩니다. 참고로 put() 메서드는 키가 새로 추가된 경우 null을 반환하고, 기존 키가 덮어써진 경우 이전에 저장되어 있던 값을 반환하므로 이 반환값을 활용하면 키의 중복 여부를 확인할 수도 있습니다.