TreeSet 底层的数据结构是二叉树,之所以能排序就是底层的二叉树被排序了。楼主,下面是饿以前写过的源代码,你看一下吧!马上就能明白了,如果还不明白可以问饿、、、构造器被作为参数传递进去了!
package yting.collection;
import java.util.*;
public class TreeSetDemo1 {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<Student>();
//TreeSet<Student> ts = new TreeSet<Student>(new strLenComparator()); //想看效果把这行代码注释去掉
//把上面那行代码注释掉
ts.add(new Student("lisi001", 11));
ts.add(new Student("lisi005", 15));
ts.add(new Student("lisi003", 13));
ts.add(new Student("lisi004", 14));
ts.add(new Student("lisi002", 12));
ts.add(new Student("lisi006", 12));
Iterator<Student> it = ts.iterator();
while(it.hasNext()) {
Student stu = (Student)it.next();
System.out.println(stu.getName()+"..."+stu.getAge());
}
}
}
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student stu) {
//这里是根据name排序的
return this.name.compareTo(stu.getName());
}
}
//这个比较器是根据age排序的
class strLenComparator implements Comparator<Student> {
@Override
public int compare(Student stu1, Student stu2) {
return (stu1.getAge() - stu2.getAge())==0 ? stu1.getName().compareTo(stu2.getName()) : stu1.getAge() - stu2.getAge();
}
} |