package quickstart;
import java.util.Iterator;
import java.util.TreeSet;
/**
* Created by patkritLee on 2017/3/14.
*/
public class testTreeSet {
public static void main(String[] args){
TreeSet ts = new TreeSet();
ts.add(new Student("lisi02",22));
ts.add(new Student("lisi03",20));
ts.add(new Student("lisi04",19));
ts.add(new Student("lisi05",22));
Iterator it = ts.iterator();
while(it.hasNext()){
Student stu = (Student)it.next();
System.out.println(stu.getName()+"..."+stu.getAge());
}
}
}
class Student implements Comparable{//该接口强制让学生具备比较性。
private String name;
private int age;
Student(String name,int age){
this.name = name;
this.age = age;
}
public int compareTo(Object obj){
if(!(obj instanceof Student)){
throw new RuntimeException("不是学生对象");
}
Student s = (Student)obj;
System.out.println(this.name + "...compareTo..."+s.name);
if(this.age > s.age){
return 1;
}else if(this.age == s.age){
return this.name.compareTo(s.name);
}else{
return -1;
}
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
void setName(String name){
this.name = name;
}
void setAge(int age){
this.age = age;
}
}
TreeSet排序的第一种方式:让元素自身具备比较性。元素需要实现Comparable接口,覆盖compareTo方法。
这种方式也称为元素的自然顺序,或者叫做默认顺序。
TreeSet的第二种排序方式:当元素自身不具备比较性时,或者具备的比较性不是所需要的。这时就需要让集合自身具备比较性。
在集合初始化时,就有了比较方式。
运行结果
lisi02...compareTo...lisi02
lisi03...compareTo...lisi02
lisi04...compareTo...lisi02
lisi04...compareTo...lisi03
lisi05...compareTo...lisi03
lisi05...compareTo...lisi02
lisi04...19
lisi03...20
lisi02...22
lisi05...22
Process finished with exit code 0