java基础学习之Collections集合工具类
常用方法:
public static boolean addAll(Collection c,E …e) 向集合中添加一些元素。
public static void shuffle(List<?> list) 打乱集合顺序。
public static void sort(List list) 将集合中元素按照默认规则排序(默认是升序)
注意:
sort()方法使用的前提是:集合中存储的元素必须实现Compable接口,重写compareTo()方法。
这样的是升序:
@Override
public int compareTo(Person o) {
return this.getAge() - o.getAge();//this.XXX() - o.XXX()这样的是升序排列
}
这样是降序排列:
@Override
public int compareTo(Person o) {
return o.getAge() - this.getAge();//o.XXX()- this.Xxx()这样是降序排列
}
例子:
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Person o) {
return o.getAge() - this.getAge();
}
}
import java.util.ArrayList;
import java.util.Collections;
public class Demo {
public static void main(String[] args) {
ArrayList<Person> arrayList =new ArrayList<>();
arrayList.add(new Person("张三",18));
arrayList.add(new Person("李四",20));
arrayList.add(new Person("王五",19));
System.out.println(arrayList);//[Person{name='张三', age=18}, Person{name='李四', age=20}, Person{name='王五', age=19}]
Collections.sort(arrayList);//这里是降序排列
System.out.println(arrayList);//[Person{name='李四', age=20}, Person{name='王五', age=19}, Person{name='张三', age=18}]
}
}
public static void sort(List list, Comparator<? super T> c)
根据指定比较器产生的顺序对指定列表进行排序
Comparable和Comparator区别:
Comparable:自己(this)和别人(参数)比较,自己需要实现Comparable接口,重写比较的规则compareTo方法。
Comparator:相当于找一个第三方的裁判,比较双方。
例子
public class Student {
private String name;
private int age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Demo1 {
public static void main(String[] args) {
ArrayList<Student> arrayList =new ArrayList<>();
arrayList.add(new Student("杨幂",18));
arrayList.add(new Student("迪丽热巴",17));
arrayList.add(new Student("古力娜扎",20));
System.out.println(arrayList);//[Student{name='杨幂', age=18}, Student{name='迪丽热巴', age=17}, Student{name='古力娜扎', age=20}]
Collections.sort(arrayList, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getAge() - o1.getAge();//这样是按年龄降序排列,如果o1.getAge() - o2.getAge(),则是升序
}
});
System.out.println(arrayList);//[Student{name='古力娜扎', age=20}, Student{name='杨幂', age=18}, Student{name='迪丽热巴', age=17}]
}
}