class User { public Integer age; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User(Integer age) { this.age = age; } }
import java.util.Comparator; public class ComparatorUser implements Comparator { public int compare(Object arg0, Object arg1) { User user0=(User)arg0; User user1=(User)arg1; return user0.getAge().compareTo(user1.getAge()); } }
public static void main(String[] args) { List userlist = new ArrayList(); userlist.add(new User(4)); userlist.add(new User(1)); userlist.add(new User(3)); userlist.add(new User(0)); userlist.add(new User(5)); userlist.add(new User(5)); ComparatorUser comparator = new ComparatorUser(); Collections.sort(userlist, comparator); for (int i = 0; i < userlist.size(); i++) { User user_temp = (User) userlist.get(i); System.out.println(user_temp.getAge()); } }