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);}
Results:
5
[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