这个问题没有确切的答案喔~~~
应该是当前的add方法放入的是哪个对象,就调用哪个对象的compareTo方法,至于这个compareTo方法怎么做,就看当前这个对象的类中是如何编写这个方法的
实验代码:
public class Parent implements Comparable {
private int age = 0;
public Parent(int age){
this.age = age;
}
public int compareTo(Object o) {
System.out.println("method of parent");
Parent o1 = (Parent)o;
return age>o1.age?1:age }
}
public class Child extends Parent {
public Child(){
super(3);
}
public int compareTo(Object o) {
System.out.println("method of child");
// Child o1 = (Child)o;
return 1;
}
}
public class TreeSetTest {
public static void main(String[] args) {
TreeSet set = new TreeSet();
set.add(new Parent(3));
set.add(new Child());
set.add(new Parent(4));
System.out.println(set.size());
}
}
|