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