简体   繁体   中英

What type is a HashMap bucket

I've been digging into the HashMap implementation in Java. All values are stored in a 'bucket' that is an Entry object. I was expecting it to be a collection or am I missing something here?

Nope. Since it doesn't have to let users access the buckets through the API, HashMap gets reduced memory usage and a simpler implementation by just rolling its own very small linked list implementation internally. It could use LinkedList , but it has no need of a doubly-linked list, and it's more efficient to pack the link, the key, the value, the key's hash code, etc. into one object.

The Entry is a collection (a light-weight linked list of sorts. Not a java Collection strictly speaking). Entries can link each other.

    static class Entry<K,V> implements Map.Entry<K,V> {
    final K key;
    V value;
    Entry<K,V> next;
    final int hash;
    }

我不知道您要查看的是谁的实现,但是在OpenJDK 6版本中 ,很明显,一个Entry存储一个值,并且每个Entry形成一个链表中的节点。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM