1、三个常用方法:
<1>addAll()
<2>shuffle()
<3>sort() [两种实现方式]
2、addAll()
作用:将所有指定元素添加到指定 collection 中
<2.1>不使用addAll(),是一个个添加
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
<2.2>使用addAll
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list,"a","v","g");
3、shuffle()
作用:打乱集合中的原有顺序
<3.1>使用方式:
Collections.shuffle(list);
4、sort()
<4.0>为什么存储String或者Interger类型时,默认排序了,升序。
因为这些类都实现了comparale<>,重写了comparTo()
1、 implements Comparable<Integer>
2、 public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
<4.1>第一种实现方式:
集合存储对象实现comparable接口,重写comparTo()
public class student implements Comparable<student>{
//自定义排序规则
@Override
public int compareTo(student o) {
return this.getAge()-o.getAge();
}
}
ArrayList<student> list = new ArrayList<>();
list.add(new student("张三",18));
list.add(new student("李四",24));
list.add(new student("王五",12));
Collections.sort(list);
System.out.println(list);
<4.2>调用sort()时,sort()直接实现Comparator<>接口
ArrayList<person> arrayList = new ArrayList<>();
arrayList.add(new person("小王",17));
arrayList.add(new person("小李",25));
arrayList.add(new person("小张",12));
Collections.sort(arrayList, new Comparator<person>() {
@Override
public int compare(person o1, person o2) {
return o1.getAge()-o2.getAge();
}
});