Collections工具类-Java

常用功能

  • public static < T > bollean addAll(Collection< T > c,T…elements):往集合中添加元素
  • public static void shutffle(List<?>list):打乱顺序
  • public static < T > sort(List<?>list):按默认规则升序排序
  • public static < T > sort(List<?>list,Comparator<? Super T>):按指定规则排序

对已有类型排序

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
Collections.sort(list);
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
}

对自定义类型排序:对Comparable重写定义排序规则:this-参数(升序)

1
2
3
4
5
6
7
8
9
public class Person implements Comparable{
private String name;
private int age;
//....
@Override
public int compareTo(Object o) {
return this.getAge() - ((Person)o).getAge();//按照年龄升序
}
}
1
2
3
4
5
6
7
8
9
10
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int result = o1.getAge() - o2.getAge();
if(result == 0){//若年龄一样,则按照姓名排序
result = o1.getName().charAt(0) - o2.getName().charAt(0);
}
return result;
}
});