简体   繁体   English

TreeMap java 实现 - 放置第一个元素

[英]TreeMap java implementation - putting 1st element

public V put(K key, V value) {
    Entry<K,V> t = root;
    if (t == null) {
        compare(key, key); // type (and possibly null) check
        root = new Entry<>(key, value, null);
        size = 1;
        modCount++;
        return null;
    }
    int cmp;
    ...
}

final int compare(Object k1, Object k2) {
    return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
        : comparator.compare((K)k1, (K)k2);
}

After facing some bug in my application, I had to debug TreeMaps put method.在我的应用程序中遇到一些错误后,我不得不调试 TreeMaps put 方法。 My issue was in comparing objects that were put in the map.我的问题是比较放置在地图中的对象。 What is odd, is that when I put FIRST element to the Map, it key gets compared with itself.奇怪的是,当我将FIRST元素放入 Map 时,它的键会与自身进行比较。 I can't understand why would it work like that.我不明白为什么会这样。 Any insights (besides the commented "type (and possibly null) check")?任何见解(除了评论的“类型(可能为空)检查”)? Why wouldn't they just check if key was null?他们为什么不检查 key 是否为空? What kind of "type" check is made out there and what for?那里进行了什么样的“类型”检查,用于什么?

As mentioned in the comment, https://bugs.openjdk.java.net/browse/JDK-5045147 is the issue where this was introduced.如评论中所述, https://bugs.openjdk.java.net/browse/JDK-5045147是引入此问题的问题。 From the discussion in that issue, the original fix was the following:根据该问题的讨论,原始修复如下:

BT2:SUGGESTED FIX BT2:建议修复

Doug Lea writes:道格·利写道:

"Thanks! I have a strong sense of deja vu that I've added this before(!) but Treemap.put should have the following trap added." “谢谢!我有一种强烈的似曾相识感,我之前已经添加了这个(!)但是 Treemap.put 应该添加了以下陷阱。”

 public V put(K key, V value) { Entry<K,V> t = root; if (t == null) { + if (key == null) { + if (comparator == null) + throw new NullPointerException(); + comparator.compare(key, key); + } incrementSize(); root = new Entry<K,V>(key, value, null); return null; }

The intention seems to throw a NPE in case the comparator of the TreeMap is null, or the comparator does not accept null keys (which conforms to the API specification).如果TreeMap的比较器为空,或者比较器不接受空键(符合 API 规范),则意图似乎抛出 NPE。 It seems the fix was shortened to one line:似乎修复被缩短为一行:

compare(key, key);

which is defined as:定义为:

@SuppressWarnings("unchecked")
final int compare(Object k1, Object k2) {
    return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
        : comparator.compare((K)k1, (K)k2);
}

Hence this test will do both the null check and the type check, namely the cast to Comparable .因此,此测试将同时进行空检查和类型检查,即转换为Comparable

I believe this is the place where TreeMap< K,V > checks if K implements Comparable if no Comparator is supplied.我相信这是TreeMap< K,V >在没有提供Comparator情况下检查K实现Comparable You get a ClassCastException otherwise.否则你会得到一个ClassCastException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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