本帖最后由 小石姐姐 于 2018-7-26 16:25 编辑
Collections常用方法总结
java.util.Collections,是不属于java的集合框架的,它是集合类的一个工具类/帮助类。此类不能被实例化,服务于java的Collection框架。 它包含有集合操作的静态多态方法,实现对各种集合的搜索、排序、线程安全等操作。
常用的方法有:
(1)排序sort(Collection) [AppleScript] 纯文本查看 复制代码
如Collections.sort(List<T> list),Collections.sort(List<T>list, Comparator<? super T> c)。
使用sort方法可以根据元素的自然顺序对指定列表按升序进行排序。列表中的所有元素都必须实现Comparable接口,而且必须是使用指定比较器可相互比较的。
(2)混排shuffle(Collection)如Collections.shuffle(List<?>list) 基于随机源的输入随机排序该List,这个算法对实现一个碰运气的游戏非常有用,在生成测试案例时也十分有用。例如斗地主的发牌,要将牌的顺序打乱,就使用了混排。举例: [AppleScript] 纯文本查看 复制代码 ArrayList<String> poker=new ArrayList<>();
//定义两个数组集合分别存储花色和数字
String[] colors={"♠","♥","♣","♦"};
String[] number={"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
//增强for循环形成牌
for (String color : colors) {
for (String num : number) {
poker.add(color+num);
}
}
//把大小王加进去
poker.add("大王");
poker.add("小王");
long end1=System.currentTimeMillis();
System.out.println("====准备牌完毕,用时"+(end1-start1)+"毫秒,洗牌开始!====");
//用Collections工具类中混排的方法,进行洗牌
Collections.shuffle(poker);
(3)反转reverse(Collection)[AppleScript] 纯文本查看 复制代码 如Collections.reverse(List<?>list)
使用reverse()反转集合中元素的顺序
(4)替换所有元素 fill(List list,Object o)使用指定元素替换集合中的所有元素。
(5)拷贝copy(List list1,List list2)
将集合list2中的元素全部复制到list1中,并且覆盖相应索引的元素。目标list1至少与源list2一样长。
(6)rotate(List list,int m)
根据指定的距离m循环移动列表中的元素。集合中的元素向后移m个位置,在后面被遮盖的元素循环到前面来。
(7)最小(大)元素min(),max()
[AppleScript] 纯文本查看 复制代码 根据指定比较器产生的顺序,返回给定Collection的最小(大)元素。
min(Collection),min(Collection,Comparator)
max(Collection),max(Collection,Comparator)
(8)indexOfSublist(List list,List sublist)查找sublist在list中首次出现位置的索引。返回指定源列表中第一次出现指定目标列表的起始位置。
(9)lastIndexOfSublist(List list,List sublist)
返回指定列表中最后一次出现指定目标列表的起始位置。
(10)swap(List list,int m,int n)交换集合中指定元素索引m,n的位置。
|
|