应该是没有针对问题的确切的答案,当前的add方法放入的是哪个对象,就调用哪个对象的compareTo方法,至于这个compareTo方法怎么做,就看当前这个对象的类中是如何编写这个方法的

试验如下:

public class TreeSetTest {
  
    /**
     * @param args
     */
    public static void main(String[] args) {
       // TODO Auto-generated method stub
       TreeSet set = new TreeSet();
       set.add(new Parent(3));
       set.add(new Child());
       set.add(new Parent(4));
       System.out.println(set.size());
    }
    public static class Parent implements Comparable {
        private int age = 0;
        public Parent(int age){
           this.age = age;
        }
        public int compareTo(Object o) {
           // TODO Auto-generated method stub
           System.out.println("method of parent");
           Parent o1 = (Parent)o;
           return age>o1.age?1:age<o1.age?-1:0;
        }
      
    }
      
    public static class Child extends Parent {
      
        public Child(){
           super(3);
        }
        public int compareTo(Object o) {
      
               // TODO Auto-generated method stub
               System.out.println("method of child");
//             Child o1 = (Child)o;
               return 1;
      
        }
    }
}

运行结果:

method of parent
method of child
method of parent
method of parent
3

相关文章:

  • 2018-04-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
  • 2022-12-23
猜你喜欢
  • 2021-08-04
  • 2021-11-19
  • 2022-12-23
  • 2021-12-20
  • 2021-09-06
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案