Collections介绍
Collections 是一个操作 Set、List 和 Map 等集合的工具类。
Collections 中提供了一系列静态的方法对集合元素进行排序、查询和修改等操作,还提供了对集合对象设置不可变、对集合对象实现同步控制等方法。
排序操作(均为static方法,且主要针对List接口)
reverse(List):反转 List 中元素的顺序
shuffle(List):对 List 集合元素进行随机排序 (洗牌)
sort(List):根据元素的自然顺序对指定 List 集合元素按升序排序
sort(List,Comparator):根据指定的 Comparator 产生的顺序对 List 集合元素进行排序
swap(List,int, int):将指定 list 集合中的 i 处元素和 j 处元素进行交换
rotate(List list, int distance):将所有元素向右移位指定长度,如果distance等于size那么结 果不变
查找和替换(主要针对Collection接口)
Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
Object max(Collection,Comparator):根据 Comparator 指定的顺序,返回给定集合中的最大元素
Object min(Collection)
Object min(Collection,Comparator)
int frequency(Collection,Object):返回指定集合中指定元素的出现次数
void copy(List dest,List src):将src中的内容复制到dest中
boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换 List 对象的所有旧值
同步控制
Collections 类中提供了多个 synchronizedXxx() 方法,该方法可使将指定集合包装成线程同步的集合,从而可以解决多线程并发访问集合时的线程安全问题。
HashSet、ArrayList、HashMap都是线程不安全的,如果需要考虑同步,则使用这些方法。这些方法主要有:synchronizedSet、 synchronizedSortedSet、synchronizedList、synchronizedMap、synchronizedSortedMap。
特别需要指出的是,在使用迭代方法遍历集合时需要手工同步返回的集合。
Map m = Collections.synchronizedMap(new HashMap());
//...
Set s = m.keySet(); // Needn't be in synchronized block
//...
synchronized (m) { // Synchronizing on m, not s!
Iterator i = s.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
}
设置不可变集合
Collections有三类方法可返回一个不可变集合:
emptyXxx():返回一个空的不可变的集合对象
singletonXxx():返回一个只包含指定对象的,不可变的集合对象。
unmodifiableXxx():返回指定集合对象的不可变视图
public void testUnmodifiable() {
System.out.println("给定的list:" + list);
List unmodList = Collections.unmodifiableList(list);
unmodList.add("再加个试试!"); // 抛出:java.lang.UnsupportedOperationException
// 这一行不会执行了
System.out.println("新的unmodList:" + unmodList);
}
其它
disjoint(Collection c1, Collection c2) :如果两个指定 collection 中没有相同的元素,则 返回 true。
addAll(Collection c, T... a) : 一种方便的方式,将所有指定元素添加到指定 collection 中。
示范:Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
Comparator reverseOrder(Comparator cmp) :返回一个比较器,它强行反转指定比较器 的顺序。
如果指定比较器为 null,则此方法等同于 reverseOrder()(换句话说,它返回一个比 较器,该比较器将强行反转实现 Comparable 接口那些对象 collection 上的自然顺序)。