TreeSet.add()方法一细节

来源:互联网 发布:如何完美卸载软件 编辑:程序博客网 时间:2024/05/22 10:54
TreeSet.add()方法一细节
   最近在一次使用TreeSet.add()方法中遇到了一个很迷惑的问题:往一个TreeSet集合中添加几个对象的时候发现有些没有添加进去,一开始是怀疑hashcode与equals的问题,因为Set集合是不允许添加两个相同对象的,但经查检确认没有问题,几经测试发现是传入的Comporator对象引起的(即使用的是TreeSet(Comparator<? super E> comparator)构造方法),当其compare()方法返回0时,只能添加进一个对象,只要当前添加的对象与集合中的任意一个对象比较时compare()方法返回0,那么该对象就添加不进去。以前一直以为compare()方法返回0时只是两个对象的排列顺序不确定,后经查看源码才明白其中的原因。
  下面是TreeSet的add()方法源码:
public boolean add(E e) {return m.put(e, PRESENT)==null;}

其中m是一个TreeMap对象,其为TreeSet的实现是使用TreeMap的key部分来实现的,PRESENT是一个Object对象,纯粹是为了补全方法参数而已,下面是TreeMap.put()方法源码:
public V put(K key, V value) {    Entry<K,V> t = root;//根元素    if (t == null) {    // TBD:    // 5045147: (coll) Adding null to an empty TreeSet should    // throw NullPointerException    //    // compare(key, key); // type check        root = new Entry<K,V>(key, value, null);        size = 1;        modCount++;        return null;    }    int cmp;    Entry<K,V> parent;    // split comparator and comparable paths    Comparator<? super K> cpr = comparator;    if (cpr != null) { //如果传入了比较器        do {            parent = t;            cmp = cpr.compare(key, t.key);  //比较两个元素的key值,也就是Set中元素的值            if (cmp < 0) //如果小于0则放到当前元素的左边                t = t.left;            else if (cmp > 0) //如果大于0则放到当前元素的右边                t = t.right;            else                return t.setValue(value);  //否则,即返回0时调用java.util.TreeMap.Entry.setValue(value)方法        } while (t != null);    }    //后面代码省略......}
下面是java.util.TreeMap.Entry.setValue(value)方法源码:
public V setValue(V value) {    V oldValue = this.value;    this.value = value;    return oldValue;}

可以看到更新了值后把以前的值返回了。所以当compare方法的返回值为了时,TreeMap.put()方法只是返回的是被替换掉的值,根本就没有加入新的元素,当然m.put(e, PRESENT)==null 返回的也为false了。


0 0
原创粉丝点击