标签:java
import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Java对象排序 */ public class User implements Comparable<User> { private int idx; public User(int idx) { this.idx = idx; } public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } @Override public String toString() { return "User{" + "idx=" + idx + ‘}‘; } @Override public int compareTo(User o) { return idx - o.idx; } public static void main(String[] args) { User a1 = new User(1); User a2 = new User(2); User a3 = new User(3); User a4 = new User(4); List<User> userList = new ArrayList<>(4); userList.add(a3); userList.add(a2); userList.add(a4); userList.add(a1); Collections.sort(userList); //排序后彻底改变原集合元素次序 for (User user : userList) { System.out.println(user); } } }
User{idx=1} User{idx=2} User{idx=3} User{idx=4} Process finished with exit code 0
本文出自 “熔 岩” 博客,请务必保留此出处http://lavasoft.blog.51cto.com/62575/1873167
标签:java
原文地址:http://lavasoft.blog.51cto.com/62575/1873167