Java提供了一个操作Set、List和Map等集合的工具类:Collections,该工具提供了大量方法对集合元素进行排序、查询和修改等操作,还提供了将集合对象设置为不可变、对集合对象实现同步控制等方法。
此类完全可以在 collection 上进行操作或返回 collection 的静态方法组成。它包含在 collection 上操作的多态算法,即“包装器”,包装器返回由指定 collection 支持的新 collection,以及少数其他内容。
Collections常用方法
方法 | 说明 |
---|---|
void reverse(List list) | 反转指定列表中元素的顺序 |
void shuffle(List list) | 对List集合元素进行随机排序 |
void sort(List list) | 根据元素的自然顺序对指定List集合的元素按升序进行排序 |
void sort(List list,Comparator c) | 根据指定Comparator产生的顺序对List集合元素进行排序 |
void swap(List list,int i,int j ) | 将指定List集合中的i处元素和j处元素进行交换 |
void rotate(List list, int distance) | 当distance为正数时,将list集合的后distance个元素“整体”移到前面;当distance为负数时,将list集合的前distance个元素“整体”移到后面;该方法不会改变集合的长度 |
1.排序sort()、存储位置打乱(随机)shuffle()、元素交换swap()
public static void main(String[] args){
List<String> L = new ArrayList<>();
L.add("a");
L.add("d");
L.add("c");
L.add("e");
L.add("h");
System.out.println("集合未处理的输出");
System.out.println(L);
//对集合元素进行排序
Collections.sort(L);
System.out.println("集合排序后的输出");
System.out.println(L);
//把集合元素存储位置打乱
Collections.shuffle(L);
System.out.println("集合打乱后的输出");
System.out.println(L);
//元素交换
Collections.swap(L, 3, 4);
System.out.println("元素位置交换后输出");
System.out.println(L);
}
输出结果:
集合未处理的输出
[a, d, c, e, h]
集合排序后的输出
[a, c, d, e, h]
集合打乱后的输出
[c, d, h, e, a]
元素位置交换后输出
[c, d, h, a, e]
集合打乱输出的(随机),其实这只是用默认的随机排列方式,我们也可以自己写一个Random对其进行随机排列。
2. 取最大值max()
List<String> L = new ArrayList<>();
L.add("a");
L.add("d");
L.add("c");
L.add("e");
L.add("h")