Collcetion是一个集合接口,它提供了对集合对象进行基本操作的通用接口方法。实现该接口的类主要有List和Set,该接口的设计目标是为各种具体的集合提供最大化的统一操作方式。
Collections是针对集合类的一个包装类,它提供了一系列的静态方法以实现对各种集合的搜索、排序、线程安全化等操作,其中大多数方法都是用来处理线性表。 Collections类不能实例化,如同一个工具类,服务于Collection。若是在使用Collections类的方法时候,对应的collection的对象为null,则这些方法都会抛出 NullPointerException 。之前我们见到的包装类还有Arrays,它是为数组提供服务的。
以下是Collections的常用方法:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestCollections {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0 ;i<5;i++){
list.add("a"+i);
}
System.out.println(list); //输出 [a0, a1, a2, a3, a4]
//Collections.shuffle(list); //1、将list随机排列
//System.out.println(list); //输出[a2, a3, a0, a1, a4]
Collections.reverse(list); //2、将集合中的内容逆序
System.out.println(list); //输出 [a4, a3, a2, a1, a0]
Collections.sort(list); //3、将集合中的内容进行排序
System.out.println(list); //输出[a0, a1, a2, a3, a4]
Collections.fill(list,"hello world"); //4、填充集合
System.out.println(list); //输出[hello world, hello world, hello world, hello world, hello world]
}
}