import java.util.*;
/*
TreeSet是有序的 在存入对象的过程中,要定义按照什么来排序
存入的类要实现一个Comparable接口
方法compareTo 大于 返回正数
小于 返回负数
等于 返回零
*/
public class Demo
{
public static void main(String[] args)
{
TreeSet ts= new TreeSet(new Comp());
ts.add(new Person("hk3",13));
ts.add(new Person("hk1",11));
ts.add(new Person("hk2",12));
ts.add(new Person("hk4",12));
ts.add(new Person("hk4",12));
ts.add(new Person("hk0",10));
Iterator it=ts.iterator();
while(it.hasNext())
{
Person p=(Person)it.next();
sop(p.getName()+" "+p.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class Comp implements Comparator //比较器。。。。。。。。。。
{
public int compare(Object o1,Object o2)
{
Person p1=(Person)o1;
Person p2=(Person)o2;
int num =p1.getName().compareTo(p2.getName());
if (num==0)
{
return p1.getAge()-p2.getAge();
}
return num;
}
}
class Person implements Comparable //比较性
{
private String name;
private int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void setAge(int age)
{
this.age=age;
}
public int getAge()
{
return age;
}
public int compareTo(Object obj) //这里!!!这里这里!!
{
if(!(obj instanceof Person))
throw new RuntimeException("shaazhes");
Person p=(Person)obj; //要转换成相同类型的才能进行比较
//System.out.println(this.age+"-----"+p.age); //比较过程
if(this.age>p.age)
return 1;
if(this.age==p.age)
{
return this.name.compareTo(p.name); //当年龄一样时 再比较一次姓名
}
return -1;
}
}
TreeSet比较器
最新推荐文章于 2025-06-17 20:29:01 发布