1、问题描述:现有user实体,有名称name和age两个属性,先想实现对arrayList<User>数组按照年龄进行排序。
2、user实体代码如下,重写tostring方法方便排序后数组的输出。
User
package com.fengshu.test.action; import org.junit.Test; public class User implements Comparable<User> { private String name; private int age; @Test public void fengshu() { double i = 4.0; String s = String.valueOf(i); System.out.print(s); } User(String _name, int _age) { name = _name; age = _age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int compareTo(User o) { return name.compareTo(o.getName()); } public String toString() { return name; } }
3、排序类如下
View Code
package com.fengshu.test.action; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import org.junit.Test; public class SortUser implements Comparator<User> { @Test public void sort() { SortUser sortUser = new SortUser(); sortUser.sort(); } public static void main(String[] args) { ArrayList<User> userList = new ArrayList<User>(); User[] users = new User[5]; users[0] = new User("fengshu", 4); users[1] = new User("feng", 9); users[2] = new User("lizhifeng", 5); users[3] = new User("jim", 33); for (int i = 0; i < 4; i++) { userList.add(i, users[i]); } //Collections.sort(userList); Collections.sort(userList, new SortUser()); System.out.print(userList); } @Override public int compare(User o1, User o2) { return o1.getAge()-o2.getAge(); } }