[Java learning notes] <Collection framework> TreeSet, Comparable, Comparator, and treesetcomparator
1 public class Person implements Comparable {2 private String name; 3 private int age; 4 5 public Person () {6 super (); 7} 8 public Person (String name, int age) 9 {10 super (); 11 this. name = name; 12 this. age = age; 13} 14 15 16 @ Override17 public int hashCode () {18 19 return name. hashCode () + age * 27; 20} 21 @ Override22 public boolean equals (Object obj) {23 if (this = obj) 24 return true; 25 if (! (Obj instanceof Person) 26 throw new ClassCastException ("type error"); 27 28 Person p = (Person) obj; 29 30 return this. name. equals (p. name) & this. age = p. age; 31} 32 @ Override33 public String toString () {34 35 return name + ":" + age; 36} 37 public String getName () {38 return name; 39} 40 public void setName (String name) {41 this. name = name; 42} 43 public int getAge () {44 return age; 45} 46 public void setAge (I Nt age) {47 this. age = age; 48} 49 @ Override50 public int compareTo (Object o) {// first by age, then by name 51 52 Person p = (Person) o; 53 54 int temp = this. age-p. age; 55 56 return temp = 0? This. name. compareTo (p. name): temp; 57 58 59} 60 61 62}
1 import java. util. comparator; 2 3 import cn. itcast. p1.bean. person; 4 5 public class ComparatorByName implements Comparator {// first by name, then by age 6 7 @ Override 8 public int compare (Object o1, Object o2) {9 Person p1 = (Person) o1; 10 Person p2 = (Person) o2; 11 12 int temp = p1.getName (). compareTo (p2.getName (); 13 14 return temp = 0? P1.getAge ()-p2.getAge (): temp; 15} 16 17}
1 import java. util. iterator; 2 import java. util. treeSet; 3 4 import cn. itcast. p1.bean. person; 5 import cn. itcast. p5.comparator. comparatorByName; 6 7 public class TreeSetDemo {8 9 public static void main (String [] args) {10 // demo1 (); 11 TreeSet ts = new TreeSet (new ComparatorByName (); // Add new ComparatorByName (). Result 1 is displayed. If this parameter is removed, result 2 is displayed.
// Comparator takes precedence over Comparable
12 13 ts. add (new Person ("zhangsan", 28); 14 ts. add (new Person ("lisi", 21); 15 ts. add (new Person ("zhouqi", 29); 16 ts. add (new Person ("zhaoliu", 25); 17 ts. add (new Person ("wangwu", 24); 18 ts. add (new Person ("lisi", 21); 19 ts. add (new Person ("zhouqi", 29); 20 21 Iterator it = ts. iterator (); 22 23 while (it. hasNext () 24 {25 Person p = (Person) it. next (); 26 27 System. out. println (p); 28} 29 30} 31 32 public static void demo1 () {33 TreeSet ts = new TreeSet (); 34 35 ts. add ("abc"); 36 ts. add ("zaa"); 37 ts. add ("aa"); 38 ts. add ("nba"); 39 ts. add ("CBA"); 40 41 Iterator it = ts. iterator (); 42 43 while (it. hasNext () 44 {45 System. out. println (it. next (); 46} 47} 48 49}