Collections.sort的使用方法有二种:
一种是:重新写一个类进行Comparator接口compare方法重写
建立Java文件 User.java 代码如下:注意(int没有compareTo方法,需要将int改成Integer)
1 public class User {
2 private String name;
3 private Integer age;
4 public User(String nameTemp,Integer ageTemp)
5 {
6 this.name = nameTemp;
7 this.age = ageTemp;
8 }
9 public String getName() {
10 return name;
11 }
12 public void setName(String name) {
13 this.name = name;
14 }
15 public Integer getAge() {
16 return age;
17 }
18 public void setAge(Integer age) {
19 this.age = age;
20 }
21 }
建立SortTest.java文件
1 import java.util.ArrayList;
2 import java.util.Collections;
3 import java.util.Comparator;
4 import java.util.List;
5
6 public class TestSort {
7 @SuppressWarnings("unchecked")
8 public static void main(String args[]) {
9 List userlist = new ArrayList();
10 userlist.add(new User("dd", 4));
11 userlist.add(new User("aa", 1));
12 userlist.add(new User("ee", 5));
13 userlist.add(new User("bb", 2));
14 userlist.add(new User("ff", 5));
15 userlist.add(new User("cc", 3));
16
17 Collections.sort(userlist, new Comparator(){
18 public int compare(Object arg1, Object arg2) {
19 User u1 = (User)arg1;
20 User u2 = (User)arg2;
21 int flag = u1.getAge().compareTo(u2.getAge());
22 return flag;
23 }
24 });
25
26 for (int i = 0; i < userlist.size(); i++) {
27 User user_temp = (User) userlist.get(i);
28 System.out.println(user_temp.getAge() + "," + user_temp.getName());
29 }
30 }
31 }
另一种是:在实体对象中实现Comparable接口
建立user.java类
1 public class User implements Comparable<User> {
2 private String name;
3 private Integer age;
4 public User(String nameTemp,Integer ageTemp)
5 {
6 this.name = nameTemp;
7 this.age = ageTemp;
8 }
9 public String getName() {
10 return name;
11 }
12
13 public void setName(String name) {
14 this.name = name;
15 }
16
17 public Integer getAge() {
18 return age;
19 }
20
21 public void setAge(Integer age) {
22 this.age = age;
23 }
24 public String toString() {
25 return "name is "+name+" age is "+age;
26 }
27 public int compareTo(User o) {
28 return this.age.compareTo(o.getAge());
29 }
30 }
建立TestSort.java文件
1 import java.util.ArrayList;
2 import java.util.Collections;
3 import java.util.List;
4
5 public class TestSort {
6 @SuppressWarnings("unchecked")
7 public static void main(String args[]) {
8 List userlist = new ArrayList();
9 userlist.add(new User("dd", 4));
10 userlist.add(new User("aa", 1));
11 userlist.add(new User("ee", 5));
12 userlist.add(new User("bb", 2));
13 userlist.add(new User("ff", 6));
14 userlist.add(new User("cc", 3));
15
16 Collections.sort(userlist);
17 for (int i = 0; i < userlist.size(); i++) {
18 User user_temp = (User) userlist.get(i);
19 System.out.println(user_temp.getAge() + "," + user_temp.getName());
20 }
21 }
22 }
posted on 2013-01-17 11:36
ForMeBlog 阅读(1730)
评论(0) 编辑 收藏 所属分类:
Java