import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new MyCompare());
ts.add(new Student("a1",12));
ts.add(new Student("a3",15));
ts.add(new Student("a2",11));
ts.add(new Student("a4",18));
Iterator it = ts.iterator();
while (it.hasNext())
{
Student st = (Student)it.next();
sop(st.getName()+","+st.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class MyCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int num = s1.getName().comparteTo(s2.getName());
if (num==0)
{
return new Integer(s1.getAge()).comparteTo(new Integer(s2.getAge()));
}
return num;
}
}
class Student implements Comparable
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Object obj)
{
Student st = (Student)obj;
if(this.age==st.age)
{
return this.name.compareTo(st.name);
}
if(this.age>st.age)
return 1;
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
为什么??求解
|
|