/*
要求:定义一个TreeSet集合,然后给TreeSetDemo里添加对象
*/
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet tr=new TreeSet();
tr.add(new Person("lisi1",17));
tr.add(new Person("lisi2",27));
tr.add(new Person("lisi3",77));
tr.add(new Person("lisi4",17));
System.out.println(tr);
}
}
class Person implements Comparable//该接口强制性的让人具备比较性
{
private String name;
private int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public int comparaTo(Object obj)
{
if (!(obj instanceof Person))
{
throw new RuntimeException("不是人这个对象");
}
else
{
Person s=(Person)obj;
if(this.age>s.age)
{
return 1;
}
if(this.age<s.age)
{
return -1;
}
return 0;
}
}
} |