本帖最后由 孙利川 于 2012-4-1 16:54 编辑
import java.util.*;
class Student
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class MyComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
int num = s1.getAge()-s2.getAge();
if (num==0)
{
return s1.getName().compareTo(s2.getName());
}
return num;
}
}
class Test
{
public static void main(String[] args)
{
Student stu0 = new Student("student1", 10);
Student stu1 = new Student("student2", 30);
Student stu2 = new Student("student3", 20);
Student stu3 = new Student("student4", 50);
Student stu4 = new Student("student5", 40);
Student stu5 = new Student("student6", 22);
// 集合对象
List list = new ArrayList();
// 添加元素
list.add(stu0);
list.add(stu1);
list.add(stu2);
list.add(stu3);
list.add(stu4);
list.add(stu5);
System.out.println("排序前:");
printList(list);
Collections.sort(list,new MyComparator());
System.out.println("排序后:");
printList(list);
}
public static void printList(List<Student> list)
{
Iterator<Student> it = list.iterator();
while (it.hasNext())
{
Student s = it.next();
System.out.println("name="+s.getName()+"\tage="+s.getAge());
}
}
}
|