Custom sorting of TreeSet

Source: Internet
Author: User

1 compare () is consistent with hashcode () and Equals ()

@Test//Custom Sorting    Public voidTestTreeSet2 () {//1. Create an anonymous class object that implements the comparator interfaceComparator com =NewComparator () {//add an object of the student class to TreeSet, in this compare method, indicate which property of the customer is sorted by         Public intCompare (Object o1,object O2) {if(O1instanceofStudent && O2instanceofStudent) {Student S1=(Student) O1; Student S2=(Student) O2; inti = S1.getid ()-S2.getid (); if(i==0){                    returns1.getname (). CompareTo (S2.getname ()); }                Else{                    returni; }            }            return0;    }    }; //2. Passing this object as a parameter to the TreeSet constructorTreeSet set =NewTreeSet (COM); //3. Add the class object involved in the Compare method to TreeSetSet.add (NewStudent (001, "Shang")); Set.add (NewStudent (005, "SFDG")); Set.add (NewStudent (006, "SHDSF")); Set.add (NewStudent (031, "Xvz")); Set.add (NewStudent (031, "ADF")); //Set.add (New Student (031, "ADF"));System.out.println (Set.size ()); SYSTEM.OUT.PRINTLN (set);}


[Student [Id=1, Name=shang], Student [id=5, NAME=SFDG], Student [Id=6, NAME=SHDSF], Student [id=25, NAME=ADF], Student [ID =25, Name=xvz]]

Custom sorting of TreeSet

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: 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.