//TreeSet<>集合要类具有比较性,或传一个比较器.
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
class TreeSetDemo
{
public static void main(String[] args)
{
//让类自已具有比较性
// TreeSet ts = new TreeSet();
TreeSet ts = new TreeSet(new Mycomparator());
//用比较器
ts.add(new Student("lisi02",22));
ts.add(new Student("lisi03",23));
ts.add(new Student("lisi04",24));
ts.add(new Student("lisi05",25));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName()+"...."+stu.getAge());
}
}
}
//用比较器
class Mycomparator implements Comparator<Student>
{
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
int rel=o1.getAge()-o2.getAge();
if(rel==0)
return o1.getName().compareTo(o2.getName());
return rel;
}
}
//让类自已具有比较性
class Student implements Comparable<Student>
{
@Override
public int compareTo(Student o)
{
int rel=this.age-o.age;
if(rel==0)
return this.name.compareTo(o.name);
return rel;
};
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
} |