Collections工具类
Collections工具类为集合服务,其常用方法有:
1.static < T > boolean addAll(Collection< T > c,T… elements)向集合中添加一些元素。
2.static void shuffle(List< ? > lsit)打乱集合顺序
3.static < T > sort(List< T > list)将集合中元素按照默认规则排序
4.static < T > sort(List< T > list,Comparator<? super T>)将集合中元素按照指定规则排序
eg:
1,2:
public static void main(String[] args) {
//1.static < T > boolean addAll(Collection< T > c,T... elements)向集合中添加一些元素。
//2.static void shuffle(List< ? > lsit)打乱集合顺序
ArrayList<String> arr = new ArrayList<>();
//1
Collections.addAll(arr,"a","b","c","d","e","f");
System.out.println(arr);
//2
Collections.shuffle(arr);
System.out.println(arr);
}
3:类需要实现Comparable< T >接口,并重写int compareTo(T o)方法。
//Person类
public class Person implements Comparable<Person> {
private String name;
private int age;
@Override
public int compareTo(Person o) {
return this.getAge() - o.getAge();//按年龄升序
//return o.getAge() - this.getAge();//降序
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + 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;
}
}
//main
public static void main(String[] args) {
ArrayList<String> strs = new ArrayList<>();
Collections.addAll(strs, "abc", "bcd", "cde", "def", "efg");
Collections.sort(strs);
System.out.println(strs);
//public int compareTo(T o)
ArrayList<Person> people = new ArrayList<>();
people.add(new Person("张三", 15));
people.add(new Person("张si", 116));
people.add(new Person("张五", 17));
people.add(new Person("张六", 18));
Collections.sort(people);
System.out.println(people);
}
4.需自定义比较方式,重写Comparator< T >接口中的 < T >int compare(T o,T o)方法。
//stduent类正常方式
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;
}
}
//main
public static void main(String[] args) {
ArrayList<Student> srr = new ArrayList<>();
srr.add(new Student("yayay",15));
srr.add(new Student("lala",16));
srr.add(new Student("haha",16));
srr.add(new Student("mimi",55));
//匿名对象,重写比较方法
Collections.sort(srr, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int result = o1.getAge() - o2 .getAge();
if (o1.getAge() == o2.getAge()){
result = o1.getName().charAt(0) - o2.getName().charAt(0);
}
return result;
}
});
System.out.println(srr);
}