"To achieve a natural ordering, the object collection must implement the comparable interface and override the CompareTo () method
The general requirements describe the "main conditions", such as: Sort by name length. Note the secondary conditions such as: the length of the same time, the name of the content, age and other conditions are equal, which determines whether to deposit TreeSet collection.
PackageCn.itcast.day21.treeset;/** To achieve a natural ordering, it is important to implement the comparable interface, and rewrite the CompareTo () method * * If the comparable interface is not implemented, and the object is added to the TreeSet, it will be reported classcastexception * cause: Java.util.TreeMap.put (treemap.java:542) * COMPARABLE<? Super k> K = (comparable<? Super K>) key;//key= collection element, forcibly converted to interface type **/ Public classStudentImplementsComparable<student>{ PrivateString name; Private intAge ; PublicStudent () {Super(); } PublicStudent (String name,intAge ) { Super(); This. Name =name; This. Age =Age ; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } @Override Public intcompareTo (Student o) {intnum= This. GetName (). Length ()-o.getname (). Length (); intNum2=num==0? This. GetName (). CompareTo (O.getname ()): num; intNum3=num2==0? This. Getage ()-o.getage (): num2; returnnum3; }}
PackageCn.itcast.day21.treeset;ImportJava.util.TreeSet;/** TreeSet According to custom object student name Length natural Sort * * * Analysis: * A: To achieve natural ordering, the class of the element will implement the comparable interface, and rewrite the CompareTo () method * B: Main Condition name length * C: Secondary condition name content, age*/ Public classTreesetdemo { Public Static voidMain (string[] args) {//To create a collection objectTreeset<student> ts=NewTreeset<student>(); //Creating an Element objectStudent s1=NewStudent ("Linqingxia", 27); Student S2=NewStudent ("Wuqilong", 27); Student S3=NewStudent ("Wanglihong", 34); Student S4=NewStudent ("Zhouxingchi", 57); Student S5=NewStudent ("Linqingxia", 28); Student S6=NewStudent ("Linqingxia", 27); //adding a collection elementTs.add (S1); Ts.add (S2); Ts.add (S3); Ts.add (S4); Ts.add (S5); Ts.add (S6); //iterating through the collection for(Student s:ts) {System.out.println (S.getname ()+"-----"+s.getage ()); } }}/**operation Result: Wuqilong-----27linqingxia-----27linqingxia-----28wanglihong-----34zhouxingchi-----*/
Natural ordering of TreeSet (custom object CompareTo method)