TreeSet底层是二叉树结构通过元素的自然比较方法排序,也可以在创建集合的时候传入比较器,这里实现比较器Compareator
import java.util.*;
class TreeDemo
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet(new MyCompare());
ts.add(new Student("lisi",12));
ts.add(new Student("lisi",13));
ts.add(new Student("lis4",12));
for(Iterator it=ts.iterator();it.hasNext();){
Student st=(Student)it.next();
System.out.println(st.getName());
}
}
}
class Student
{
private String name;
private int age;
public Student(String name,int age){
this.name=name;
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
class MyCompare implements Comparator//实现comparator接口
{
public int compare(Object o1,Object o2)//复写compare方法
{
if(!(o1 instanceof Student&&o2 instanceof Student)){
throw new RuntimeException("yixhang ");}
Student s1,s2;
s1=(Student)o1;
s2=(Student)o2;
int num= s1.getName().compareTo(s2.getName());
if (num==0)
{
return s1.getAge()-s2.getAge();
}
return num;
}
}
|
|