黑马程序员技术交流社区
标题:
关于在TreeSet里面放对象的问题!
[打印本页]
作者:
张业婷
时间:
2014-10-2 19:42
标题:
关于在TreeSet里面放对象的问题!
如果在TreeSet中同时放入了父类和子类的实例对象,那比较时使用的是父类的compareTo方法,还是使用的是
子类的compareTo方法,还是抛异常啊?
作者:
zuochbd
时间:
2014-10-2 21:08
本帖最后由 caixingke 于 2014-10-2 21:20 编辑
你得看下TreeSet的源代码.
非首次add时会进行比较的, 我们就以add方法来看.
TreeSet内部实现的本质是TreeMap.
所以, 我们看下TreeMap的put方法就可以知晓了:
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;
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);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key; //注意
do {
parent = t;
cmp = k.compareTo(t.key); //注意
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
复制代码
这句话:Comparable<? super K> k = (Comparable<? super K>) key;
这句话:
cmp = k.compareTo(t.key);
即, 用的是你添加的那个元素的comparable的方法来决定的.
即, 如果添加的是子类的元素, 并且子类重写了父类的comparable的comparaTo方法, 那么就用子类的comparaTo方法.
就这样
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2