TreeSet會調用元素的compareTo(Object o)方法來比較元素之間的大小關係,而後將集合裏的元素按升序排列.此時須要排序元素的類必須實現Compareble接口,並覆寫其int compareTo(Object o)方法;java
該方法用於比較對象,若:obj1,compareTo(obj2),返回0,表示兩個對象相等,若返回一個正整數,表示obj1大於obj2,若返回一個負整數,表示obj1小於obj2;ide
對於TreeSet集合而言,判斷兩個對象相等的標準是:this
compareTo()方法比較返回 0;對象
package july7;排序
//TreeSet能夠自動進行排序!最簡單的狀況接口
import java.util.Set;it
import java.util.TreeSet;class
public class Demo13 {import
public static void main(String[] args) {泛型
Set<Integer> s = new TreeSet<Integer>();
s.add(1);
s.add(192);
s.add(123);
s.add(56);
s.add(13);
s.add(96);
System.out.println(s);//[1, 13, 56, 96, 123, 192]
}
}
稍複雜點的
package july7;
//TreeSet的天然排序,升序
import java.util.Set;
import java.util.TreeSet;
class Student implements Comparable{//必須實現接口
private Integer age;
public Student(Integer age) {
super();
this.age = age;
}
@Override
public int compareTo(Object o) {//比較的規則,運用泛型能夠消除強轉!
if(o instanceof Student){
Student s = (Student)o;
return this.age.compareTo(s.age);
}
return 0;
}
@Override
public String toString() {
return age+"" ;
}
}
public class Demo14 {
public static void main(String[] args) {
Set<Student> s = new TreeSet();
s.add(new Student(140));
s.add(new Student(15));
s.add(new Student(11));
s.add(new Student(63));
s.add(new Student(96));
System.out.println(s);//[11, 15, 63, 96, 140]
}
}