首先讲一下Comparable接口和Comparator接口,以及他们之间的差异。有助于Collections.sort()方法的使用。请参考
1.Comparable自然规则排序
//在自定义类Student里面实现Comparable接口,并重写抽象方法compareTo(User u);
//Collections.sort(集合);
实例:
public static void main(String[] args) {
List<Integer> nums = new ArrayList<Integer>();
nums.add(3);
nums.add(5);
nums.add(1);
nums.add(0);
System.out.println(nums);
Collections.sort(nums);
System.out.println(nums);
}
输出结果:
[3, 5, 1, 0]
[0, 1, 3, 5]
稍微复杂的List里面放一个复杂的对象
public class ListTest {
public static void main(String[] args) {
List<User> list = new ArrayList<User>();
User u1 = new User(1,"张三丰");
User u2 = new User(2,"王重阳");
User u3 = new User(3,"郭靖");
User u4 = new User(4,"1");
User u5 = ne