Posts [Java] HashMap vs HashSet
Post
Cancel

[Java] HashMap vs HashSet

HashMap

  • Key : Value 형태
  • 내부는 Node 객체를 이용해서 구현되어 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    ...
}

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

final V putVal(
    int hash, 
    K key, 
    V value, 
    boolean onlyIfAbsent, 
    boolean evict
) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);

    ...
}

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

final Node<K,V> removeNode(
    int hash, 
    Object key, 
    Object value, 
    boolean matchValue, 
    boolean movable
) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;

        ...
    }

    ...
}


HashSet

  • Key : Value(Dummy value) 형태
  • 내부는 HashMap을 이용해서 구현되어 있다.
1
2
3
4
5
6
7
8
9
10
11
12
private transient HashMap<E,Object> map;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}


References

  • HashMap 내부 코드
  • HashSet 내부 코드
This post is licensed under CC BY 4.0 by the author.