HashMap과 Hashtable

Jay Jang·2022년 8월 5일
0

Java

목록 보기
5/5

이 글을 읽기 위해선 해시 테이블 자료구조를 먼저 이해하고 있어야 한다. 몰랐다면, 잠시 읽고 오자.

Java에는 key-value 형태로 데이터를 다루는 자료구조, map이 존재한다.

map의 대표적인 자료구조가 두 개 있는데, HashMapHashtable이다. 사용 방법이 비슷하기도 하지만, 큰 차이점도 존재한다.

HashMapHashtable의 차이점을 알아보자.

HashMap, Hashtable 사용 예제


// 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

출처: https://memostack.tistory.com/233

HashMap


HashMap동기화 synchronized를 지원하지 않는다. 때문에 thread-safe 하지 않아 단일 스레드 환경에서 사용하기에 적합한 자료구조이다.

// 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);
}

HashMap을 사용하면서도 동기화 synchronized 처리를 해서 type-safe를 가져갈 수 있다. 이 때는 ConcurrentHashMap을 사용한다.

ConcurrentHashMapHashtable과는 달리 클래스 전체에 synchronized 처리가 되어있지 않다. 읽기 get 작업에는 동기화 처리하지 않으며, put과 같은 쓰기 작업에만 동기화 처리한다.

Hashtable은 legacy class이고, HashMap은 이를 발전시켜 Java 1.2부터 지원된 class이다. 일반적인 케이스에서 Hashtable을 사용하는 것 보다 HashMap을 사용하는 것이 권장된다고 한다.

또한 HashMap은 key, value에 null을 허용한다.

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

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

Hashtable


Hashtable동기화 synchronized를 지원하여, thread-safe 하다.
때문에 멀티스레드 환경에서도 사용하기 좋은 자료구조라고 할 수 있다.

반면 이 동기화 때문에, blocking 후 unblock 까지 대기해야 하기 때문에 HashMap에 비해 성능상 느리다.

// 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)

Conclusion



https://www.javastudypoint.com/2019/03/java-hashtable-with-example.html

HashMap은 동기화 되지 않는다. 따라서 thread safe하지 않다.
Hashtable은 동기화 되어 있다. 따라서 thread safe하다.

HashMap은 key, value에 대해서 null 값을 허용한다.
Hashtable은 key, value 어느 것에도 null을 허용하지 않는다.

HashMap은 빠르다. 동기화 되어있지 않기 때문.
Hashtable은 느리다. 동기화 되어 있기 때문.

HashMap은 iterator 클래스를 통해 탐색할 수 있다.
Hashtable은 iterator와 Enumeration 모두를 통해 탐색할 수 있다.

HashMap은 Java 1.2부터 도입되었다.
Hashtable은 legacy 클래스이다.

HashMap은 AbstractMap 클래스를 상속한다.
Hashtable은 Dictonary 클래스를 상속한다.


REFERENCE


https://www.javastudypoint.com/2019/03/java-hashtable-with-example.html
https://memostack.tistory.com/233#1.%20HashMap

profile
그때는맞고지금은틀리다

0개의 댓글