看出来问题的大神,请不吝赐教,谢谢!
实现代码如下:
package views;
import java.util.*;
public class Test3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Collection<Student> ss=new TreeSet<Student>();
ss.add(new Student(18,"B"));
ss.add(new Student(18,"A"));
ss.add(new Student(19,"a"));
ss.add(new Student(19,"a"));
ss.add(new Student(20,"f"));
ss.add(new Student(20,"a"));
ss.add(new Student(16,"B"));
ss.add(new Student(17,"A"));
Iterator< Student> it=ss.iterator();
Student stu1=null;
while(it.hasNext())
{
stu1=it.next();
System.out.println(stu1.getAge()+"----"+stu1.getName());
}
}
}
class Student implements Comparator<Student> {
private int age=0;
private String name =null;
public Student (int age,String name){
this.age=age;
this.name=name;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
public int compare(Student obj1,Student obj2)
{
if(obj1.getAge()==obj2.getAge())
return obj1.getName().compareTo(obj2.getName()) ;
return obj1.getAge()-obj2.getAge();
}
} |