Collections集合工具类
特点:构造私有,方法都是静态的,通过类名直接调用
static <T> boolean addAll(Collection<? super T> c, T... elements)
作用:批量添加元素
public class Test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Collections.addAll(list,1,2,3,4,5,6,7,8,9);
System.out.println(list);
}
}
static void shuffle(List<?> list)
作用:将集合中的元素顺序打乱
public class Test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Collections.addAll(list,1,2,3,4,5,6,7,8,9);
System.out.println(list);
Collections.shuffle(list); //顺序打乱
System.out.println(list);
}
}
static <T> void sort(List<T> list)
作用: 将集合中的元素按照ASCII码表所对应的数字排序,如果第一个字符一样,会按照第二个字符的ASCII码表去排列
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("aB李四");
list.add("aA张三");
list.add("aC王五");
Collections.sort(list);
System.out.println(list);
}
}
static <T> void sort(List<T> list, Comparator<? super T> c)
Comparator比较器
作用:通过Comparator比较器将集合中的元素按照指定规则排序。int compare(T o1,T o2) o1-o2是升序,o2-o1是降序
首先创建一个Person类包含name、age私有成员变量,实现set()get()等方法
public class Test {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("张三",666));
list.add(new Person("李四",66));
list.add(new Person("王五",6));
Collections.sort(list, new Comparator<Person>() { //通过匿名内部类指定按什么规则去排序
@Override
public int compare(Person o1, Person o2) {
return o1.getAge()-o2.getAge();
}
});
System.out.println(list);
}
}
重写Comparable接口的compareTo()
int compareTo(T o)方法中this-o是升序,o-this是降序。
public class Person implements Comparable<Person>{
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public int compareTo(Person o) {
return this.getAge()-o.getAge();
}
}
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("张三",888));
list.add(new Person("李四",88));
list.add(new Person("王五",8));
Collections.sort(list);
System.out.println(list);
}