TreeSet里面放對象,如果同時放入了父類和子類的實例對象,那比較時使用的是父類的compareTo方法,還是使用的子類的compareTo方法,還是拋異常!


/**
 *
 * @author ocq
 */
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 o1 = (Parent) o;
        return age > o1.age ? 1 : age < o1.age ? -1 : 0;
    }
}

class Child extends Parent{

    public Child() {
        super(3);
    }

   public int compareTo(Object o) {
        System.out.println("method of 子");
        return 1;
    }
}

public class ComparableTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        TreeSet set = new TreeSet();
       set.add(new Parent(3));
        set.add(new Child());
         set.add(new Child());
        set.add(new Parent(4));
        System.out.println(set.size());
//        測試結果:
//        如果子類和父類都復寫了compareTo方法那么各自調用自己的compareTo方法
//        如果子類沒有復寫compareTo方法,那么調用的都是父類的compareTo方法    
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM