Why HashMap uses TreeNode for not Comparable keys?

被刻印的时光 ゝ 提交于 2019-12-22 09:54:29

问题


I know that in Java 8 HashMap was optimized for poorly distributed hashCode. And in cases when threshold was exceeded it rebuilds nodes in bucket from linked list into tree. Also it is stated that this optimization doesn't work for not comparable keys (at leas performance is not improved). In the example below I put not Comparable keys into HashMap

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

class Main {
    public static void main(String[] args) throws InterruptedException {
        Map<Key, Integer> map = new HashMap<>();

        IntStream.range(0, 15)
                .forEach(i -> map.put(new Key(i), i));

        // hangs the application to take a Heap Dump
        TimeUnit.DAYS.sleep(1);
    }
}

final class Key {
    private final int i;

    public Key(int i) {
        this.i = i;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Key key = (Key) o;
        return i == key.i;
    }

    @Override
    public int hashCode() {
        return 1;
    }
}

But Inspecting the Heap Dump shows that nodes was rearrange into Tree.

My question is why nodes is rebuilt into the tree if it will not improve performance and on which criteria in this case nodes is compared to figure out which key should be right node and which left?


回答1:


I think that you sort of misunderstood what that answer was saying. Comparable is not needed, it's just an optimization that might be used when hashes are equal - in order to decide where to move the entry - to the left or to the right (perfectly balanced red-black tree node). Later if keys are not comparable, it will use System.identityHashcode.

figure out which key should be right node and which left

It goes to the right - the bigger key goes to the right, but then the tree might need to be balanced. Generally you can look-up the exact algorithm of how a Tree becomes a perfectly balanced red black tree, like here



来源:https://stackoverflow.com/questions/45117319/why-hashmap-uses-treenode-for-not-comparable-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!