java.utils.Collections:是集合工具类
作用:Collection并不属于集合,是用来操作集合的工具类
方法名称
public static <T> boolean addAll(Collection<? super T> c,T...element) 给集合对象批量添加元素
public static void shuffle(List<?> List) 打乱List集合元素的顺序
public static <T> int binarySearch(List<T> List, T key) 以二分查找法查找元素
public static <T> void max/min(Collection<T> coll) 根据默认的自然排序获取最大/最小
public static <T> void swap (List<?> List,int i,int j) 交换集合中指定位置的元素
package com.tools;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class CollectionsDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list,"v","r","t");
System.out.println(list);
Collections.shuffle(list);
System.out.println(list);
Collections.binarySearch(list, "r");
ArrayList<Integer> list1 = new ArrayList<>();
Collections.addAll(list1, 25, 36, 25, 25, 77, 45, 9, 4, 8, 2);
System.out.println(list1);
System.out.println(Collections.max(list1));
ArrayList<Student> listStu = new ArrayList<>();
Collections.addAll(listStu,new Student("张三",34),new Student("王五", 35));
Collections.max(listStu);
}
}
package com.tools;
import javax.xml.namespace.QName;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Student{name = " + name + ", age = " + age + "}";
}
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
}