Java中,将对象,通过add()添加到集合中,这一过程会自动调用compareTo方法吗

2025-05-22 06:35:33
推荐回答(1个)
回答1:

会的,请参阅以下:
向树中添加的时候会调用
treeSet中的:

public boolean add(E e) {
return m.put(e, PRESENT)==null; //调用NavigableMap中的put方法
}
其中m定义为:private transient NavigableMap m;
NavigableMap中的put方法定义为:
public final V put(K key, V value) {
if (!inRange(key))
throw new IllegalArgumentException("key out of range");
return m.put(key, value); //调用TreeMap中的put方法
}
其中的m是个TreeMap
treeMap中的put方法截取如下:
if (key == null)
throw new NullPointerException();
Comparable k = (Comparable) 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);