import java.util.*;
class Student
{
private int age;
private String name;
public Student(String name,int age)
{
this.age=age;
this.name=name;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
public boolean equals(Object obj)
{
if(obj instanceof Student)
{
Student s=(Student)obj;
if(s.getAge()==this.getAge() && s.getName().equals(this.getName()))
return true;
return false;
}
return false;
}
}
class TestTree
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet(new MyCompare());
ts.add(new Student("susan",24));
ts.add(new Student("susan",21));
ts.add(new Student("lisi",21));
Iterator it=ts.iterator();
while(it.hasNext())
{
Student s=(Student)it.next();
System.out.println(s.getAge()+"..."+s.getName());
}
}
}
class MyCompare implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Student s1=(Student)obj1;
Student s2=(Student)obj2;
int num=new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
if(num==0)
return s1.getName().compareTo(s1.getName());
return num;
}
}
我往集合中添加了三个对象,为什么输出的时候之输出两个呢
|
-
1.png
(1.27 KB, 下载次数: 50)
|