Collections
- 是一个用来操作集合的工具类
Collections提供的常用静态方法
代码演示
import com.zeyu.object.Collection.Set.Student;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CollectionsTest1 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
//1、public static <T> boolean addAll(Collection<? super T> c,...elemenr为集合批量添加数据
Collections.addAll(list,"小白","小红","小黑","小绿","小青","小蓝");
System.out.println(list); //[小白, 小红, 小黑, 小绿, 小青, 小蓝]
//2、public static void shuffle(List<?>list):打乱List集合中的元素顺序。
Collections.shuffle(list);
System.out.println(list); //[小蓝, 小绿, 小红, 小黑, 小白, 小青]
//3、 public static <T>void sort(List<T>list):对List集合中的元素进行升序排序。
List<Integer> nums = new ArrayList<>();
Collections.addAll(nums,3,56,4,7,1);
Collections.sort(nums);
System.out.println(nums); //[1, 3, 4, 7, 56]
// 4、public static <T> void sort(List<T> list,Comparator<?superT>c):对List集合中元素,按照比较器对象指定的规则进行排序
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("小明","男",170));
students.add(new Student("小美","女",168));
students.add(new Student("小黑","男",188));
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return Double.compare(o1.getHeight(),o2.getHeight());
}
});
System.out.println(students); //[Student{name='小美', sex='女', height='168.0'}, Student{name='小明', sex='男', height='170.0'}, Student{name='小黑', sex='男', height='188.0'}]
}
}
运行结果: