Natural sorting of TreeSet (custom object compareTo method), treesetcompareto
To implement natural sorting, the object set must implement the Comparable interface and override the compareTo () method.
"General requirements are described as" main conditions ", such as sorting by name length. Note that secondary conditions such as the same length, name content, age, and other conditions are equal, which determines whether to store the data in the TreeSet set.
Package cn. itcast. day21.treeset;/** to implement natural sorting, you must implement the Comparable interface and override the compareTo () method. ** if you do not implement the Comparable interface, add the object to the TreeSet, classCastException * cause: java. util. treeMap. put (TreeMap. java: 542) * Comparable <? Super K> k = (Comparable <? Super K>) key; // key = set element, forcibly converted to interface type **/public class Student implements Comparable <Student> {private String name; private int age; public Student () {super ();} public Student (String name, int age) {super (); this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int Age) {this. age = age ;}@ Override public int compareTo (Student o) {int num = this. getName (). length ()-o. getName (). length (); int num2 = num = 0? This. getName (). compareTo (o. getName (): num; int num3 = num2 = 0? This. getAge ()-o. getAge (): num2; return num3 ;}}
Package cn. itcast. day21.treeset; import java. util. treeSet;/** TreeSet sorts Student names and lengths of custom objects in A natural order. ** analysis: * A: To achieve natural sorting, the Comparable interface must be implemented for element classes, and override the compareTo () method * B: Name Length of the main condition * C: Name content of the secondary condition, age */public class TreeSetDemo {public static void main (String [] args) {// create a collection object TreeSet <Student> ts = new TreeSet <Student> (); // create an element object Student s1 = new Student ("linqingxia", 27 ); student s2 = new Student ("wuqilong", 27); Student s3 = new Student ("wanglihong", 34); Student s4 = new Student ("zhouxingchi", 57 ); student s5 = new Student ("linqingxia", 28); Student s6 = new Student ("linqingxia", 27); // Add a set element ts. add (s1); ts. add (s2); ts. add (s3); ts. add (s4); ts. add (s5); ts. add (s6); // traverses the set for (Student s: ts) {System. out. println (s. getName () + "-----" + s. getAge () ;}}/ ** running result: wuqilong ----- 27linqingxia ----- 27linqingxia ----- 28wanglihong ----- 34zhouxingchi ----- 57 */