TreeSet底层是一个二叉树结构,其中元是不可重复的。而且存入其中的对象必须具有可比性,无比较性对象会抛出类型转换异常利用的是compareTo方法做的比较 相等则返回0
TreeSet排序有两种情况
1、让元素自身具备比较性,也就是元素要实现comparable接口,覆盖compareTo()方法 这是元素的自然顺序
2、当元素自身不具备比较性时或者具备的比较性不是所需的,就需要集合TreeSet自身具备比较性 在集合初始化时就有了比较方式,需要定义一个比较器作为参数传递给 TreeSet集合
首先分析Student对象,这是一个不具备比较性的对象可以利用方法一让它实现一个comparable接口
Person类
public static class Student implements Comparable{
private String name;
private int age;
public int compareTo(Object obj){
if(!(obj instanceof Student)){
throw new RuntimeException("传的类型不对");
}
Student s=(Student) obj;
if(this.age>s.age){
return 1;
}
if(this.age==s.age){
return this.name.compareTo(s.name);
}
return -1;
}
Student(String name,int age){
this.name=name;
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
实现存储
public class TreeSetCompare {
public static void main(String[] args) {
TreeSet ts=new TreeSet();
// TreeSet ts=new TreeSet(new MyCompare());
ts.add(new Student("zhangsan",23));
ts.add(new Student("zhangsan2",22));
ts.add(new Student("zhangsan2",25));
ts.add(new Student("zhangsan3",22));//他一compareTo发现相同就不存了 解决:判断次要条件
ts.add(new Student("lisi",25));
Iterator it=ts.iterator();
while(it.hasNext()){
Student s=(Student)it.next();
System.out.println(s.getName()+"----"+s.getAge());
}
}
}
方法二 自定义一个比较器
public static class MyCompare implements Comparator{
//用来比较传入的两个对象
public int compare(Object obj1,Object obj2){
if(!(obj1 instanceof Student)||!(obj2 instanceof Student))
{
throw new RuntimeException("传值不正确");
}
Student s1=(Student)obj1;
Student s2=(Student)obj2;
int num= s1.name.compareTo(s2.name);
if(num==0)//不能判断为1或-1 因为相同时返回0 大于返回正数小于返回一个负数
{
//判断一下age
return new Integer(s1.age).compareTo(s2.age);
}
return num;
}
}
把实现存储代码中的注释打开TreeSet ts=new TreeSet();注释上即可
注意:当自定义比较器和实现Comparable接口 复写compareTo方法同时存在时 以自定义比较器为主