日期:2014-05-20 浏览次数:20953 次
import java.util.*;
class SetType {
int i;
public SetType(int n) { i = n; }
public boolean equals(Object o) {
return o instanceof SetType && (i == ((SetType)o).i);
}
public String toString() { return Integer.toString(i); }
}
class TreeType extends SetType
implements Comparable<TreeType> {
public TreeType(int n) { super(n); }
public int compareTo(TreeType arg) {
System.out.println("arg.i= " + arg.i + " i= " + i); //关键看这里
return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));
}
}
public class TypesForSets {
static <T> Set<T> fill(Set<T> set, Class<T> type) {
try {
for(int i = 0; i < 2; i++)
set.add(
type.getConstructor(int.class).newInstance(i));
} catch(Exception e) {
throw new RuntimeException(e);
}
return set;
}
static <T> void test(Set<T> set, Class<T> type) {
fill(set, type);
fill(set, type); // Try to add duplicates
fill(set, type);
System.out.println(set);
}
public static void main(String[] args) {
test(new TreeSet<TreeType>(), TreeType.class);
}
}
return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));
------解决方案--------------------
树状结构
第一次fill
插0不比较 树为 0
插1和0比较1次 树为 0
|
1
第二次fill
插0时和已插入的0比较1次
插1时先和0比较,再和1比较, 比较2次
第三次fill同第二次
所以一共比较了7次
------解决方案--------------------
第一次调用fill:
尝试将“0”添加到TreeSet对象:由于TreeSet对象为空,直接将0作为TreeSet对象的根节点。
尝试将“1”添加到TreeSet对象:与TreeSet对象的根节点比较,输出 arg.i= 0 i= 1。
根节点没有子节点,于是将“1”添加为“0”的左子节点。
第二次调用fill:
尝试将“0”添加到TreeSet对象:与根节点“0”比较,输出 arg.i= 0 i= 0。
由于“0”已经是TreeSet中的元素,此时不会添加新的节点。
尝试将“1”添加到TreeSet对象:与根节点“0”比较,输出 arg.i= 0 i= 1。
与子节点“1”比较,输出 arg.i= 1 i= 1。
由于“1”已经是TreeSet中的元素,此时不会添加新的节点。
第三次调用fill与第二次调用fill执行的步骤完全一致。