List<Long> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(Math.round(Math.random()*10)); } // 升序 Collections.sort(list); // 降序 Collections.sort(list,Collections.reverseOrder()); for (Long i : list) { System.out.println(i); }
publicclassMain{ publicstaticvoidmain(String[] args){ List<User> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(new User(i)); } Collections.sort(list); for (User user : list) { System.out.println(user.id); } }
staticclassUserimplementsComparable{ int id;
publicUser(){ }
publicUser(int id){ this.id = id; } // 升序:this > o,返回1;相等返回0;this < o,返回-1 // 降序:this > o,返回-1;相等返回0;this < o,返回1 @Override publicintcompareTo(Object o){ User user = (User) o; if (id > user.id) { return1; } elseif (id == user.id) { return0; } else { return -1; } } } }