memostack
article thumbnail
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
반응형

HashMapHashtable 모두 map 자료구조다.

  • 사용 방법도 거의 동일하지만, 차이점이 있음
// HashMap
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");

System.out.println(map.get(1)); // one
System.out.println(map.get(2)); // two

// Hashtable
Map<Integer, String> table = new Hashtable<>();
table.put(1, "one");
table.put(2, "two");

System.out.println(table.get(1)); // one
System.out.println(table.get(2)); // two

 

HashMap

HashMap은 동기화를 지원하지 않는다.

  • 단일스레드 환경에서 사용하기 좋은 자료구조

 

IDE의 구현부를 보면, 아래 Hashtable과는 다르게 synchronized 키워드가 없음

// get method
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}
    
// put method
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

 

또, HashMapkey 값이나 value 값에 null이 들어갈 수 있음

Map<Integer, String> map = new HashMap<>();
map.put(null, "null");

System.out.println(map.get(null)); // null

 

Hashtable

Hashtable은 동기화를 지원하여, thread-safe하다.

  • 멀티스레드 환경에서 사용하기 좋은 자료구조
  • 하지만, HashMap에 비해 느리다. (다른 스레드가 block되고 unblock 되는 대기 시간을 기다리기 때문)

 

IDE를 이용해 구현부를 보면 synchronized 키워드가 붙어있다.

// get method
public synchronized V get(Object key) {
    // ... 중략 ...
}
    
// put method
public synchronized V put(K key, V value) {
    // ... 중략 ...
}

 

또, Hashtable은 key값이나 value값에 null이 들어갈 수없다.

Map<Integer, String> table = new Hashtable<>();
table.put(null, "null");
// Exception in thread "main" java.lang.NullPointerException
//	at java.util.Hashtable.put(Hashtable.java:465)
//	at Main.main(Main.java:10)

 

HashMap과 Hashtable의 차이

반응형
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
profile

memostack

@bluemiv_mm

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!