一、Collections类的应用
介绍 :Collections是一个类,用于操作集合类(如List,Set)的工具类,就如同Arrays是数组的工具类
常用方法:
关键字----------------------------简介
reverse--------------------------反转
shuffle---------------------------混淆
sort-------------------------------排序
swap-----------------------------交换
rotate----------------------------滚动
synchronizedList—线程安全化
示例代码:
List<Integer> arry = new ArrayList<Integer>();
for (int i = 0; i <10; i++) {
arry.add(i);
}
//颠倒
Collections.reverse(arry);
//排序
Collections.sort(arry);
//交换
Collections.swap(arry, 0, 5);
//滚动
Collections.rotate(arry, 2);
//线程安全
List<Integer> synchronizedList = Collections.synchronizedList(arry);
/*
* 统计概率
* 首先初始化一个List,长度是10,值是0-9。
* 然后不断的shuffle,直到前3位出现
* 3 1 4
* 运行1万次,统计概率
* */
int count = 0;
for (int i = 0; i < 10000; i++) {
//混淆
Collections.shuffle(arry);
if(arry.get(0).equals(3) && arry.get(1).equals(1)
&& arry.get(2).equals(4)) {
count++;
}
//混淆
Collections.shuffle(arry);
}
System.out.printf("运行一万次,共出现: %d次" , count);
】