有Person類如下: 有main如下: 由於TreeSet為可排序集合,所以要為存放對象(Person)指定排序規則。 排序規則:ASC(升序),age > address > name故重寫Person的compareTo(): 註:若要DESC排序: 1、age比較中交換1/-1; 2、add ...
有Person類如下:
1 class Person { 2 String name; 3 int age; 4 String address; 5 }
有main如下:
1 import java.util.TreeSet; 2 3 public class Test{ 4 public static void main(String[] args){ 5 Person p1 = new Person("AA",18,"CN"); 6 Person p2 = new Person("BB",18,"JP"); 7 Person p3 = new Person("CC",18,"CN"); 8 9 TreeSet<Person> persons = new TreeSet<>(); 10 persons.add(p1); 11 persons.add(p2); 12 persons.add(p3); 13 for (Object person : persons) { 14 System.out.println(person); 15 } 16 } 17 }
由於TreeSet為可排序集合,所以要為存放對象(Person)指定排序規則。
排序規則:ASC(升序),age > address > name
故重寫Person的compareTo():
1 public int compareTo(Person o) { 2 if(this.age > o.age){ 3 return 1; 4 }else if(this.age < o.age) { 5 return -1; 6 } 7 //判斷age誰大,若相等,則判斷address 8 int x = this.address.compareTo(o.address); 9 if(x != 0){ 10 return x; 11 } 12 //判斷address誰大,若相等,則判斷name 13 return this.name.compareTo(o.name); 14 }
註:若要DESC排序:
1、age比較中交換1/-1;
2、address比較中return相反數值;
3、name比較中return相反數值;
上述代碼的邏輯順序:
傳入比較對象o與自身進行對比;
若this.age > o.age,返回“1”;
若this.age < o.age,返回“-1”;
若相等,比較address;
令x = this.address.compareTo(o.address);
若x != 0,即不相等,x即為要返回的值(1/-1);
若x == 0,即相等,比較name;
this.name.compareTo(o.name)的值即為要返回的值:
若值為 1,即大於,
若值為-1,即為小於,
若值為 0,即三處均相等,則完全相等,不應存入。
完整代碼:
1 package toBKY; 2 3 import java.util.TreeSet; 4 5 public class Test{ 6 public static void main(String[] args){ 7 Person p1 = new Person("AA",18,"CN"); 8 Person p2 = new Person("BB",18,"JP"); 9 Person p3 = new Person("CC",18,"CN"); 10 11 TreeSet<Person> persons = new TreeSet<>(); 12 persons.add(p1); 13 persons.add(p2); 14 persons.add(p3); 15 16 for (Object person : persons) { 17 System.out.println(person); 18 } 19 //使用for each 比Iterator代碼量少 20 21 } 22 } 23 24 class Person implements Comparable<Person>{ 25 String name; 26 int age; 27 String address; 28 29 public Person(String name, int age, String address) { 30 this.name = name; 31 this.age = age; 32 this.address = address; 33 } 34 35 @Override 36 public String toString() { 37 return "Person{" + 38 "name='" + name + '\'' + 39 ", age=" + age + 40 ", address='" + address + '\'' + 41 '}'; 42 } 43 44 @Override 45 public int compareTo(Person o) { 46 if(this.age > o.age){ 47 return 1; 48 }else if(this.age < o.age) { 49 return -1; 50 } 51 //判斷age誰大,若相等,則判斷address 52 int x = this.address.compareTo(o.address); 53 if(x != 0){ 54 return x; 55 } 56 //判斷address誰大,若相等,則判斷name 57 return this.name.compareTo(o.name); 58 } 59 }