JAVA中根据集合中对象属性排序的方法
来源:互联网 发布:淘宝联盟提现不到账 编辑:程序博客网 时间:2024/04/29 11:42
- package Collection;
-
- import java.util.*;
-
- public class Sort {
- private static ArrayList list = new ArrayList();
- private static UserBean[] user = new UserBean[4];
-
- public static void main(String[] args) {
- Sort sort = new Sort();
- user[0] = new UserBean("004",34);
- user[1] = new UserBean("003",56);
- user[2] = new UserBean("010",1);
- user[3] = new UserBean("002",22);
-
- for (int i = 0; i < 4; i++) {
- list.add(user[i]);
- }
-
- Collections.sort(list,new ReverseSort());
-
-
-
-
- for (Iterator iterator = list.listIterator();iterator.hasNext()) {
- System.out.println(((UserBean)iterator.next()).name);
- }
- }
- }
-
- class UserBean implements Comparable{
- public String name;
- public int age;
-
- public UserBean(String name,int age) {
- this.name = name;
- this.age = age;
- }
-
-
- public int compareTo(Object obj) {
- UserBean user = (UserBean)obj;
- return this.name.compareTo(user.name);
- }
- }
-
-
- class ReverseSort implements Comparator{
-
- public int compare(Object obj1,Object obj2) {
- UserBean user1 = (UserBean)obj1;
- UserBean user2 = (UserBean)obj2;
- return -user1.name.compareTo(user2.name);
- }
- }