一、常用功能
(1)Collections.addAll(集合名称,添加的多个元素)
ArrayList<String> list=new ArrayList<>();
Collections.addAll(list,"b","c","d","e");
(2)Collections.shuffle(集合名称):打乱集合顺序
Collections.shuffle(list);
(3)Collections.sort(List<T> list):将集合按照指定的顺序排序(默认是升序)
注意:sort()使用前提:
被排序的集合里面存储的元素,必须实现Comparable,重写接口中的方法compareTo定义排序的规则
重写排序的规则:return 0:认为元素都是相同的
return this.gettAge()-o.getAge() :按照年龄升序排序
return o.getAge()-this.getAge():按照年龄降序排序
自己(this)-参数:升序
public class Person implements Comparable<Person>{
private String name;
private int age;
//省略构造方法(空参,全参),getter,setter,toString
@Override
public int compareTo(Person o) {
// return 0; //认为元素都是相同的
return this.getAge()-o.getAge();//升序
// return o.getAge()-this.getAge();//降序
}
}
ArrayList<Person> list01=new ArrayList<>();
list01.add(new Person("b迪丽热巴",18));
list01.add(new Person("c杨幂",20));
list01.add(new Person("d古力娜扎",18));
System.out.println(list01); //未排序前
Collections.sort(list01);
System.out.println(list01); //排序后
(4)Collections.sort(List<T> list.Comparator<? super T>):将集合按照制定规则排序
Comparable与Comparator的区别:
Comparable:自己(this)和别人(参数)比较,自己需要实现Comparable的接口,重写比较的规则CompareTo方法
Comparator:相当于找了一个第三方裁判,比较两个 【o1-o2为升序】
public class Student {
private String name;
private int age;
//省略构造方法(空参,全参),getter,setter,toString
}
ArrayList<Student> list02=new ArrayList<>();
list02.add(new Student("b迪丽热巴",22));
list02.add(new Student("c杨幂",25));
list02.add(new Student("d古力娜扎",22));
System.out.println(list02);
Collections.sort(list02, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int result=o1.getAge()-o2.getAge();//升序排列
//若是二者年龄一样的话比较名字的第一个字母
if(result==0){
result=o1.getName().charAt(0)-o2.getName().charAt(0); //比较首字母,索引为0
}
return result;
}
});
System.out.println(list02);