集合工具类Collections
1.基本信息:
包:java,util
类型:类/包装器
如果为此类的方法所提供的 collection 或类对象为 null,则这些方法都将抛出 NullPointerException。
2.常用方法
2.1添加
// 将所有指定元素添加到指定 collection 中
addAll(Collection<? super T> c, T... elements)
2.2查找
//使用二分搜索法搜索指定列表,以获得指定对象。
binarySearch(List<? extends Comparable<? super T>> list, T key)
//使用比较器二分搜索法搜索指定列表,以获得指定对象。
binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
//返回指定源列表中第一次出现指定目标列表的起始位置;如果没有出现这样的列表,则返回 -1。
indexOfSubList(List<?> source, List<?> target)
2.3排序
//根据指定比较器产生的顺序,返回给定 collection 的最大元素。
max(Collection<? extends T> coll, Comparator<? super T> comp)
// 根据元素的自然顺序 对指定列表按升序进行排序。
sort(List<T> list)
String [] str = new String[]{"sdf","dsg","tyf","rjtk","ijg","ghhd","guisd"};
List list =Arrays.asList(str);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
>>>[sdf, dsg, tyf, rjtk, ijg, ghhd, guisd]
[dsg, ghhd, guisd, ijg, rjtk, sdf, tyf]
//根据指定比较器产生的顺序对指定列表进行排序。
sort(List<T> list, Comparator<? super T> c)
//反转指定列表中元素的顺序。
reverse(List<?> list)
String [] str = new String[]{"sdf","dsg","tyf","rjtk","ijg","ghhd","guisd"};
List list =Arrays.asList(str);
System.out.println(list);
Collections.sort(list);
Collections.reverse(list);
System.out.println(list);
>>>[sdf, dsg, tyf, rjtk, ijg, ghhd, guisd]
[tyf, sdf, rjtk, ijg, guisd, ghhd, dsg]
//随机打乱列表内元素顺序
public static void shuffle(List<?> list,Random rnd)
String [] str = new String[]{"sdf","dsg","tyf","rjtk","ijg","ghhd","guisd"};
List list =Arrays.asList(str);
System.out.println(list);
Collections.shuffle(list);
System.out.println(list);
>>>[sdf, dsg, tyf, rjtk, ijg, ghhd, guisd]
[ghhd, rjtk, tyf, sdf, ijg, guisd, dsg] //(随机出现的,不一定是这个)
2.4比较
//如果两个指定 collection 中没有相同的元素,则返回 true。
disjoint(Collection<?> c1, Collection<?> c2)
//返回指定 collection 中等于指定对象的元素数。
frequency(Collection<?> c, Object o)
2.5替换
//使用指定元素替换指定列表中的所有元素。
fill(List<? super T> list, T obj)
//使用另一个值替换列表中出现的所有某一指定值。
replaceAll(List<T> list, T oldVal, T newVal)
//在指定列表的指定位置处交换元素。
swap(List<?> list, int i, int j)
2.6移动
//根据指定的距离轮换指定列表中的元素。
rotate(List<?> list, int distance)
假设 list 包含 [a, b, c, d, e]。要将索引 1 处的元素(b)向前移动两个位置,请执行以下调用:
Collections.rotate(list.subList(1, 4), -1);
得到的列表是 [a, c, d, b, e]。