Java集合(1):Collections工具类中的static方法

与Arrays一样,Collections类中也有一些实用的static方法。

 

(1) 排序操作

reverse(List list):反转指定List集合中元素的顺序

shuffle(List list):对List中的元素进行随机排序(洗牌)

sort(List list):对List里的元素根据自然升序排序

sort(List list, Comparator c):自定义比较器进行排序

swap(List list, int i, int j):将指定List集合中i处元素和j出元素进行交换

rotate(List list, int distance):将所有元素向右移位(轮转)指定长度,如果distance等于size那么结果不变

Comparator<T> reverseOrder():返回一个比较器反转指定容器

Comparator<T> reverseOrder(Comparator<T> cmp):返回一个比较器,它强行反转指定比较器的顺序

 

(2)添加查找和替换

addAll(Collection<? super T> c, T... a):一种方便的方式,将所有指定元素添加到指定collection中

binarySearch(List list, Object key):使用二分搜索法,以获得指定对象在List中的索引,前提是集合已经排序

disjoint(Collection c1, Collection c2):如果两个指定collection中没有相同的元素,则返回true

max(Collection coll):返回最大元素

max(Collection coll, Comparator comp):根据自定义比较器,返回最大元素

min(Collection coll):返回最小元素

min(Collection coll, Comparator comp):根据自定义比较器,返回最小元素

fill(List list, Object obj):使用指定对象填充(复制此对象的引用来填充整个容器)

frequency(Collection coll, Object o):返回指定集合中指定对象出现的次数

replaceAll(List list, Object old, Object new):替换集合中对象为指定新对象

 

(3)同步控制

Collections工具类中提供了多个synchronizedXxx方法,该方法返回指定集合对象对应的同步对象,从而解决多线程并发访问集合时线程的安全问题。

HashSet、ArrayList、HashMap都是线程不安全的,如果需要考虑同步,则使用这些方法。这些方法主要有:

synchronizedCollection(Collection coll)

synchronizedList(List list)

synchronizedSet(Set set)

synchronizedMap(Map map)

synchronizedSortedSet(SortedSet set)

synchronizedSortedMap(SortedMap map)


(4)设置不可变集合

emptyXxx():返回一个空的不可变的集合对象

singletonXxx():返回一个只包含指定对象的,不可变的集合对象

unmodifiableXxx():返回指定集合对象的read-only的视图,并随着指定集合对象的改变而改变

posted @ 2018-02-08 18:13  Storm_L  阅读(395)  评论(0编辑  收藏  举报