java.util.Collections
静态方法:
public static <T> boolean addAll(Collection<T> c, T...elements):往集合中添加一些元素
public static void shuffle(List<?> list):打乱集合的顺序
public static void sort(List<?> list):默认升序,只能传递List,不能传递、Set,如果对自定义类排序,必须实现接口Comparable,重写compareTo方法
public ststic <T> void sort(List<T> list, Comparator<? super T>) : 将集合元素按照指定规则排序
public class Demo01Collections {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c", "d");
System.out.println(list);// [a, b, c, d]
Collections.shuffle(list);// 打乱顺序
System.out.println(list);// [b, c, d, a],每次调用都是随机打乱
}
}
package cn.zhuobo.day10.aboutCollections;
public class Person implements Comparable<Person>{
private String name;
private int age;
//重写compareTo方法,自定义比较规则,现在是按照年龄升序排序
@Override
public int compareTo(Person o) {
return this.getAge() - o.getAge();//自己-参数就是升序,反之就是降序
}
public ststic void sort(List list, Comparator<? super T>) : 将集合元素按照指定规则排序
public class Demo01Collections {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("aaa", 18));
list.add(new Person("bbb", 16));
list.add(new Person("ccc", 18));
list.add(new Person("ddd", 15));
System.out.println(list);
Collections.sort(list);
System.out.println(list);
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int result = o2.getAge() - o1.getAge();//第二个-第一个(按照年龄降序)
if(result == 0) result = o1.getName().charAt(0) - o2.getName().charAt(0);// 如果年龄相同,按照首字符升序
return result;
}
});
System.out.println(list);
}
}