A
A
afna2016-09-03 22:31:12
Java
afna, 2016-09-03 22:31:12

How are elements added to the HashMap?

Hello!
I started to study Collections in Java in depth.
Settled on HashMap. Found an article on habr-e .
Began to check with source codes. I have Java 8.
It is clear how the hash is calculated:

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

But how do we get the position to insert into the table and where is this table not clear?
This is the element's embed code:
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);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

I believe that the new version has changed HashMap.
What is TreeNode ?
How does it all work?
This point is different from what was written in the article.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2016-09-03
@zagayevskiy

I suspect (a cursory glance, before going to sleep) that they have upgraded the collision resolution method. Previously, there were lists, now there is a kind of search tree. Dig based on this message. You have to make sure, of course.

A
Alexey, 2016-09-04
@TheKnight

https://examples.javacodegeeks.com/core-java/util/...
Maybe this article will help you?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question