集合工具类
Java提供一个操作Set, List和Map等集合的工具类:Collections。
提供大量方法对集合进行排序,查询,修改等操作。
实现集合对象的线程安全。
排序
Collections 提供下面方法对List进行排序。
- reverse():反转List顺序
- shuffle():随机排序
- sort():自然排序,可以指定Comparator排序
- swap(): 元素交换
- rotate(): distance正数时, 后面元素移到前面, 负数时,前distance个元素移到后面。
使用例子
ArrayList nums = new ArrayList();
nums.add(2);
nums.add(-4);
nums.add(8);
nums.add(0);
System.out.println(nums);
Collections.reverse(nums);
System.out.println(nums);
Collections.sort(nums);
System.out.println(nums);
Collections.shuffle(nums);
System.out.println(nums);
//Output
[2, -4, 8, 0]
[0, 8, -4, 2]
[-4, 0, 2, 8]
[0, 2, -4, 8]
查找、替换
主要提供下面方法用于查找,替换。
- binarySearch(): 使用二分查找搜索指定 List集合,要先保证List中元素已处于有序状态。
- max():返回最大值, 自然排序或指定Comparator排序
- min(): 返回最小值, 自然排序或指定Comparator排序
- fill(): 指定元素替换List中所有元素
- frequency():元素出现次数
- indexOfSubList(): 子List第一次出现的位置
- lastIndexOfSubList(): 子List最后一次出现的位置
- replaceAll():使用一个新值替换List旧值
ArrayList nums = new ArrayList();
nums.add(2);
nums.add(-4);
nums.add(8);
nums.add(0);
System.out.println(nums);
System.out.println(Collections.max(nums));
System.out.println(Collections.min(nums));
Collections.replaceAll(nums, 2, 3);
System.out.println(nums);
System.out.println(Collections.frequency(nums, 3));
Collections.sort(nums);
System.out.println(nums);
System.out.println(Collections.binarySearch(nums, 8));
//Output
[2, -4, 8, 0]
8
-4
[3, -4, 8, 0]
1
[-4, 0, 3, 8]
3
同步控制
Java中常用的集合实现类, HashSet,TreeSet, ArrayList, ArrayDeque, LinkedList, HashMap, TreeMap都是线程不安全的。
如果有多个线程访问,超过一个线程试图修改,则存在线程安全问题。
Collections提供了多个 synchronizedXxx()方法, 将指定集合包装成线程同步的集合。
Collection collection = Collections.synchronizedCollection(new ArrayList<>());
List list = Collections.synchronizedList(new ArrayList<>());
Set set = Collections.synchronizedSet(new HashSet<>());
Map map = Collections.synchronizedMap(new HashMap<>());
线程安全的集合类
在 java.util.concurrent
下提供并发访问的集合接口和实现
主要分为两类:
Concurrent开头的: 如: ConcurrentHashMap, ConcurrentSkipListMap, ConcurrentLinkedQueue.
CopyOnWrite 开头的: 如: CopyOnWriteArrayList, CopyOnWriteArraySet.
Concurrent 开头代表支持并发访问的集合,
默认情况下 ConcurrentHashMap默认支持16个线程并发写入, 可以通过 concurrentLevel构造参数设置
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable {
}
public interface ConcurrentMap<K, V> extends Map<K, V>{
}
CopyOnWriteArrayList 通过复制底层数组的方式来实现写操作。
读操作时直接读取集合本身,无需加锁和阻塞。
写操作时直接复制一份新数组,对新数组执行写入操作。因此是线程安全的。
由于频繁的复制数组,性能比较差。
不可变集合
Collections提供了不可变集合。
集合是"只读", 不能修改。
主要下面方法:
- emptyXxx(): 返回一个空的, 不可变集合
- singletonXxx(): 返回一个指定元素的不可变集合,
- unmodifiableXxx(): 返回指定集合的不可变视图。
List emptyList = Collections.emptyList();
Set ummodifySet = Collections.singleton("A");
Map score = new HashMap();
score.put("A", 100);
score.put("B", 90);
Map unmodifyMap = Collections.unmodifiableMap(score);
unmodifyMap.put("C", 30);
//Output
java.lang.UnsupportedOperationException
当试图修改时,抛出UnsupportedOperationException 异常。
地址: https://blog.csdn.net/yonggang7/article/details/86770719