java自定义排序的俩种方法
1.Comparator 定制排序
Collections.sort(arrayList, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } });
2.compare接口重写 compareTo 方法
public class Person implements Comparable<Person>{ @Override public int compareTo(Person o) { if (this.age > o.getAge()) { return 1; } if (this.age < o.getAge()) { return -1; } return 0; } }
3.传入匿名内部类的方法:
其实还是上面那俩种,只不过使用了匿名内部类
TreeMap<Person, String> treeMap = new TreeMap<>(new Comparator<Person>() { @Override public int compare(Person person1, Person person2) { int num = person1.getAge() - person2.getAge(); return Integer.compare(num, 0); } });