正确:
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Iterator;
- public class Sort {
- public static class User
- {
- String name;
- int age;
-
- public User(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public int getAge()
- {
- return age;
- }
- public void setAge(int age)
- {
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public void setName(String name)
- {
- this.name = name;
- }
-
- //重写toString实现打印User类对象
- public String toString()
- {
- return "("+name+", "+age+")";
- }
- }
-
- //实现user之间根据年龄比较大小的类
- public static class UserComparator implements Comparator
- {
- public int compare(Object arg0, Object arg1)
- {
- User user0=(User)arg0;
- User user1=(User)arg1;
- return user1.getAge()-user0.getAge();
- }
- }
-
-
- public static void main(String[] arg)
- {
- ArrayList<User> userLists = new ArrayList<User>();
- User u1 = new User("a",15);
- User u2 = new User("b",19);
- User u3 = new User("c",12);
- User u4 = new User("d",7);
- userLists.add(u1);
- userLists.add(u2);
- userLists.add(u3);
- userLists.add(u4);
-
- UserComparator comparator = new UserComparator();
- Collections.sort(userLists, comparator);
-
- Iterator<User> it = userLists.iterator();
- while(it.hasNext())
- {
- System.out.println(it.next());
- }
- }
- }
复制代码 |