TreeSet:可以對Set集合中的元素排序,默認按照ascii表排序,二叉樹結構
左邊叉是小的,右邊叉是大的
存儲自定義對象
定義一個類Student實現Comparable類,使自定義類具備比較性
定義屬性年齡age
定義屬性姓名name
實現compareTo()方法,傳遞進來另一個Student對象
判斷當前Student對象的age大於另一個Student對象的age,返回1,否則返回-1
獲取Student對對象
調用TreeSet對象的add()方法,參數:Student對象
遍歷集合
import java.util.TreeSet;
public class TreeSetDemo {
/**
* @param args
*/
public static void main(String[] args) {
TreeSet<Student> treeset=new TreeSet<Student>();
treeset.add(new Student("taoshihan1",30));
treeset.add(new Student("taoshihan2",20));
treeset.add(new Student("taoshihan3",40));
for(Student student:treeset){
System.out.println(student.name+"==="+student.age);
}
}
}
class Student implements Comparable<Student>{
public int age;
public String name;
public Student(String name,int age) {
this.name=name;
this.age=age;
}
@Override
public int compareTo(Student o) {
if(o.age<this.age){
return 1;
}else{
return -1;
}
}
}
結果:
taoshihan2===20
taoshihan1===30
taoshihan3===40