/** * * @authorOcq*/classParentImplementsComparable {Private intAge = 0; PublicParent (intAge ) { This. Age =Age ; } Public intcompareTo (Object o) {System.out.println ("Method of the parent class"); Parent O1=(Parent) o; returnAge > O1.age? 1:age < o1.age? -1:0; }}classChildextendsparent{ PublicChild () {Super(3); } Public intcompareTo (Object o) {System.out.println ("Method of Child"); return1; }} Public classComparabletest {/** * @paramargs*/ Public Static voidMain (string[] args) {TreeSet set=NewTreeSet (); Set.add (NewParent (3)); Set.add (NewChild ()); Set.add (NewChild ()); Set.add (NewParent (4)); System.out.println (Set.size ());//Test Results://if both the subclass and the parent replicate the CompareTo method, then each call their own CompareTo method//if the subclass does not have a replication CompareTo method, then the CompareTo method of the parent class is called }}
TreeSet inside the object, if you put the parent class and the subclass of the instance object, then the comparison is to use the CompareTo method of the parent class, or use the CompareTo method of the subclass, or throw an exception!