Collections 是一個操做 Set、List 和 Map 等集合的工具類。安全
Collections 中提供了一系列靜態的方法對集合元素進行排序、查詢和修改等操做,還提供了對集合對象設置不可變、對集合對象實現同步控制等方法。多線程
Collections 類中提供了多個 synchronizedXxx() 方法,該方法可以使將指定集合包裝成線程同步的集合,從而能夠解決多線程併發訪問集合時的線程安全問題。併發
static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> { private static final long serialVersionUID = 487447009682186044L; SynchronizedSet(Set<E> s) { super(s); } SynchronizedSet(Set<E> s, Object mutex) { super(s, mutex); } public boolean equals(Object o) { if (this == o) return true; // 同步代碼塊,Vector、Hashtable都是同步方法 synchronized (mutex) {return c.equals(o);} } public int hashCode() { // 同步代碼塊,Vector、Hashtable都是同步方法 synchronized (mutex) {return c.hashCode();} } }
Collections類中的方法有:dom
min()、max()、copy()、sort()、binarySearch()、reverse() —— 反轉、shuffle() —— 亂序工具
fill() ——把一個對象填充到list裏的每個單元、swap(List,int, int):交換元素this
int frequency(Collection,Object):返回指定集合中指定元素的出現次數spa
boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替換 List 對象的全部舊值線程
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) { if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) // 適用於ArrayList return Collections.indexedBinarySearch(list, key); else // 適用於LinkedList return Collections.iteratorBinarySearch(list, key); }