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!

Source: Internet
Author: User

/** * * @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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.