TreeSet中存放元素,預設按自然排序的方式去除重覆項,併進行排序的 String和8種包裝類中都指定自然排序方法:實現java.lang.Comparable介面,重寫compareTo方法 自定義的類放入TreeSet時,也實現實現java.lang.Comparable介面,重寫compar... ...
Student類:name、age屬性
1 package com.bjpowernode.test01_set2_Comparable; 2 /* 3 * T: type 4 */ 5 public class Student implements Comparable<Student> { 6 private String name; 7 private int age; 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public int getAge() { 15 return age; 16 } 17 public void setAge(int age) { 18 this.age = age; 19 } 20 public Student(String name, int age) { 21 super(); 22 this.name = name; 23 this.age = age; 24 } 25 public Student() { 26 super(); 27 // TODO Auto-generated constructor stub 28 } 29 /*@Override 30 public int hashCode() { 31 final int prime = 31; 32 int result = 1; 33 result = prime * result + age; 34 result = prime * result + ((name == null) ? 0 : name.hashCode()); 35 return result; 36 } 37 @Override 38 public boolean equals(Object obj) { 39 if (this == obj) 40 return true; 41 if (obj == null) 42 return false; 43 if (getClass() != obj.getClass())//判斷兩個“對象”的類型是否相同。 44 return false; 45 Student other = (Student) obj; //向下轉型 46 if (age != other.age) 47 return false; 48 if (name == null) { //避免出現NullPointerException異常 49 if (other.name != null) 50 return false; 51 } else if (!name.equals(other.name)) 52 return false; 53 return true; 54 }*/ 55 /* 56 * 當前對象與參數對象相同時返回 : 0 57 * 當前對象 大於參數對象 時: 1 正數 58 * 當前對象 小於參數對象 時: -1 負數 59 */ 60 @Override 61 public int compareTo(Student s) { 62 //按年齡排序,如果年齡相同,按姓名排序 63 if(this.age == s.age){ 64 //按姓名排序, 調用字元串的compareTo 65 return this.name.compareTo(s.name); 66 } 67 return this.age -s.age; 68 } 69 70 }
TreeSet存儲,遍歷,排序輸出
1 package com.bjpowernode.test01_set2_Comparable; 2 3 import java.util.TreeSet; 4 /* 5 * TreeSet中存放元素,預設按自然排序的方式去除重覆項,併進行排序的 6 * String和8種包裝類中都指定自然排序方法:實現java.lang.Comparable介面,重寫compareTo方法 7 * 自定義的類放入TreeSet時,也實現實現java.lang.Comparable介面,重寫compareTo方法 8 */ 9 public class StudentTreeSetTest { 10 public static void main(String[] args) { 11 TreeSet<Student> tree = new TreeSet<>(); 12 Student s = new Student("Mike", 18); 13 Student s1 = new Student("Join", 28); 14 Student s3 = new Student("Join", 18); 15 Student s4 = new Student("Smith", 18); 16 tree.add(s); 17 tree.add(s1); 18 tree.add(s3); 19 tree.add(s4); 20 System.out.println(tree.size()); 21 System.out.println("姓名\t年齡"); 22 for (Student stu : tree) { 23 System.out.println(stu.getName()+"\t"+stu.getAge()); 24 } 25 } 26 }