我认为Collections类主要是完成了两个主要功能
1.提供了若干简单而又有用的算法,比如排序,二分查找,求最大最小值等等。
2.提供对集合进行包装的静态方法。比如把指定的集合包装成线程安全的集合、包装成不可修改的集合、包装成类型安全的集合等。
package java.util;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
public class Collections{
// Suppresses default constructor, ensuring non-instantiability.
private Collections() {
}
// 算法
/*
*
* 算法需要用到的一些参数。所有的关于List的算法都有两种实现,一种是适合随机访问的
* List,另一种是适合连续访问的。
*/
private static final int BINARYSEARCH_THRESHOLD = 5000;
private static final int REVERSE_THRESHOLD = 18;
private static final int SHUFFLE_THRESHOLD = 5;
private static final int FILL_THRESHOLD = 25;
private static final int ROTATE_THRESHOLD = 100;
private static final int COPY_THRESHOLD = 10;
private static final int REPLACEALL_THRESHOLD = 11;
private static final int INDEXOFSUBLIST_THRESHOLD = 35;
/**
*
* List中的所有元素必须实现Compareable接口,即每个 元素必须是可比的。
*
* 算法的实现原理为:
* 把指定的List转化为一个对象数组,对数组进行排序,然后迭代List的每一个元素,
* 在同样的位置重新设置数组中排好序的元素
*/
public static
Object[] a = list.toArray(); //转化为对象数组
Arrays.sort(a); //对数组排序,使用了归并排序.对此归并的详细分析可见我另一篇博客
ListIterator
for (int j=0; j
i.next();
i.set((T)a[j]); //在同样的位置重设排好序的值
}
}
/**
* 传一个实现了Comparator接口的对象进来。
* c.compare(o1,o2);来比较两个元素
*/
public static
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator i = list.listIterator();
for (int j=0; j
i.set(a[j]);
}
}
/**
*
* 使用二分查找在指定List中查找指定元素key。
* List中的元素必须是有序的。如果List中有多个key,不能确保哪个key值被找到。
* 如果List不是有序的,返回的值没有任何意义
*
* 对于随机访问列表来说,时间复杂度为O(log(n)),比如1024个数只需要查找log2(1024)=10次,
* log2(n)是最坏的情况,即最坏的情况下都只需要找10次
* 对于链表来说,查找中间元素的时间复杂度为O(n),元素比较的时间复杂度为O(log(n))
*
* @return 查找元素的索引。如果返回的是负数表明找不到此元素,但可以用返回值计算
* 应该将key插入到集合什么位置,任然能使集合有序(如果需要插入key值的话)。
* 公式:point = -i - 1
*
*/
public static
if (list instanceof RandomAccess || list.size()
else
return Collections.iteratorBinarySearch(list, key);
}
/**
* 使用索引化二分查找。
* size小于5000的链表也用此方法查找
*/
private static
int low = 0; //元素所在范围的下界
int high = list.size()-1; //上界
while (low <= high) {
int mid = (low + high) >>> 1;
Comparable super T> midVal = list.get(mid); //中间值
int cmp = midVal.compareTo(key); //指定元素与中间值比较
if (cmp < 0)
low = mid + 1; //重新设置上界和下界
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found
}
/**
* 迭代式二分查找,线性查找,依次查找得中间值
*
*/
private static
int low = 0;
int high = list.size()-1;
ListIterator extends Comparable super T>> i = list.listIterator();
while (low <= high) {
int mid = (low + high) >>> 1;
Comparable super T> midVal = get(i, mid);
int cmp = midVal.compareTo(key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found
}
private static
T obj = null;
int pos = i.nextIndex(); //根据当前迭代器的位置确定是向前还是向后遍历找中间值
if (pos <= index) {
do {
obj = i.next();
} while (pos++ < index);
} else {
do {
obj = i.previous();
} while (--pos > index);
}
return obj;
}
/**
* 提供实现了Comparator接口的对象比较元素
*/
public static
if (c==null)
return binarySearch((List) list, key);
if (list instanceof RandomAccess || list.size()
else
return Collections.iteratorBinarySearch(list, key, c);
}
private static
int low = 0;
int high = l.size()-1;
while (low <= high) {
int mid = (low + high) >>> 1;
T midVal = l.get(mid);
int cmp = c.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found
}
private static
int low = 0;
int high = l.size()-1;
ListIterator extends T> i = l.listIterator();
while (low <= high) {
int mid = (low + high) >>> 1;
T midVal = get(i, mid);
int cmp = c.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found
}
private interface SelfComparable extends Comparable
/**
*
* 逆序排列指定列表中的元素
*/
public static void reverse(List> list) {
int size = list.size();
//如果是size小于18的链表或是基于随机访问的列表
if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
for (int i=0, mid=size>>1, j=size-1; i
swap(list, i, j); //交换i和j位置的值
} else { //基于迭代器的逆序排列算法
ListIterator fwd = list.listIterator();
ListIterator rev = list.listIterator(size);
for (int i=0, mid=list.size()>>1; i
Object tmp = fwd.next();
fwd.set(rev.previous());
rev.set(tmp);
}
}
}
/**
*
* 对指定列表中的元素进行混排
*/
public static void shuffle(List> list) {
if (r == null) {
r = new Random();
}
shuffle(list, r);
}
private static Random r;
/**
*
* 提供一个随机数生成器对指定List进行混排
*
* 基本算法思想为:
* 逆向遍历list,从最后一个元素到第二个元素,然后重复交换当前位置
* 与随机产生的位置的元素值。
*
* 如果list不是基于随机访问并且其size>5,会先把List中的复制到数组中,
* 然后对数组进行混排,再把数组中的元素重新填入List中。
* 这样做为了避免迭代器大跨度查找元素影响效率
*/
public static void shuffle(List> list, Random rnd) {
int size = list.size();
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for (int i=size; i>1; i--) //从i-1个位置开始与随机位置元素交换值
swap(list, i-1, rnd.nextInt(i));
} else {
Object arr[] = list.toArray(); //先转化为数组
//对数组进行混排
for (int i=size; i>1; i--)
swap(arr, i-1, rnd.nextInt(i));
// 然后把数组中的元素重新填入List
ListIterator it = list.listIterator();
for (int i=0; i
it.set(arr[i]);
}
}
}
/**
* 交换List中两个位置的值
*/
public static void swap(List> list, int i, int j) {
final List l = list;
l.set(i, l.set(j, l.get(i))); //互换i和j位置的值
}
/**
* 交换数组俩位置的值。好熟悉啊
*/
private static void swap(Object[] arr, int i, int j) {
Object tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/**
*
* 用obj替换List中的所有元素
* 依次遍历赋值即可
*/
public static
int size = list.size();
if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
for (int i=0; i
} else {
ListIterator super T> itr = list.listIterator();
for (int i=0; i
itr.set(obj);
}
}
}
/**
*
* 复制源列表的所有元素到目标列表,
* 如果src.size > dest.size 将抛出一个异常
* 如果src.size < dest.size dest中多出的元素将不受影响
* 同样是依次遍历赋值
*/
public static
int srcSize = src.size();
if (srcSize > dest.size())
throw new IndexOutOfBoundsException("Source does not fit in dest");
if (srcSize < COPY_THRESHOLD ||
(src instanceof RandomAccess && dest instanceof RandomAccess)) {
for (int i=0; i
} else { //一个链表一个线性表也可以用迭代器赋值
ListIterator super T> di=dest.listIterator();
ListIterator extends T> si=src.listIterator();
for (int i=0; i
di.set(si.next());
}
}
}
/**
*
* 返回集合中的最小元素。前提是其中的元素都是可比的,即实现了Comparable接口
* 找出一个通用的算法其实不容易,尽管它的思想不难。
* 反正要依次遍历完所有元素,所以直接用了迭代器
*/
public static
Iterator extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) < 0)
candidate = next;
}
return candidate;
}
/**
* 根据提供的比较器求最小元素
*/
public static
if (comp==null)
//返回默认比较器,其实默认比较器什么也不做,只是看集合元素是否实现了Comparable接口,
//否则抛出ClassCastException
return (T)min((Collection
Iterator extends T> i = coll.iterator();
T candidate = i.next(); //假设第一个元素为最小元素
while (i.hasNext()) {
T next = i.next();
if (comp.compare(next, candidate) < 0)
candidate = next;
}
return candidate;
}
/**
* 求集合中最大元素
*/
public static
Iterator extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) > 0)
candidate = next;
}
return candidate;
}
/**
* 根据指定比较器求集合中最大元素
*/
public static
if (comp==null)
return (T)max((Collection
Iterator extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (comp.compare(next, candidate) > 0)
candidate = next;
}
return candidate;
}
/**
*
* 旋转移位List中的元素通过指定的distance。每个元素移动后的位置为:
* (i + distance)%list.size.此方法不会改变列表的长度
*
* 比如,类表元素为: [t, a, n, k, s , w]
* 执行Collections.rotate(list, 2)或
* Collections.rotate(list, -4)后, list中的元素将变为
* [s, w, t, a, n , k]。可以这样理解:正数表示向后移,负数表示向前移
*
*/
public static void rotate(List> list, int distance) {
if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
rotate1((List)list, distance);
else
rotate2((List)list, distance);
}
private static
int size = list.size();
if (size == 0)
return;
distance = distance % size; //distance始终处于0到size(不包括)之间
if (distance < 0)
distance += size; //还是以向后移来计算的
if (distance == 0)
return;
for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
T displaced = list.get(cycleStart);
int i = cycleStart;
do {
i += distance; //求新位置
if (i >= size)
i -= size; //超出size就减去size
displaced = list.set(i, displaced); //为新位置赋原来的值
nMoved ++; //如果等于size证明全部替换完毕
} while(i != cycleStart); //依次类推,求新位置的新位置
}
}
private static void rotate2(List> list, int distance) {
int size = list.size();
if (size == 0)
return;
int mid = -distance % size;
if (mid < 0)
mid += size;
if (mid == 0)
return;
//好神奇啊
reverse(list.subList(0, mid));
reverse(list.subList(mid, size));
reverse(list);
}
/**
*
* 把指定集合中所有与oladVal相等的元素替换成newVal
* 只要list发生了改变就返回true
*/
public static
boolean result = false;
int size = list.size();
if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
if (oldVal==null) {
for (int i=0; i
list.set(i, newVal);
result = true;
}
}
} else {
for (int i=0; i
list.set(i, newVal);
result = true;
}
}
}
} else {
ListIterator
if (oldVal==null) {
for (int i=0; i
itr.set(newVal);
result = true;
}
}
} else {
for (int i=0; i
itr.set(newVal);
result = true;
}
}
}
}
return result;
}
/**
*
* target是否是source的子集,如果是返回target第一个元素的索引,
* 否则返回-1。
* 其实这里和串的模式匹配差不多。这里使用的是基本的回溯法。
*
*/
public static int indexOfSubList(List> source, List> target) {
int sourceSize = source.size();
int targetSize = target.size();
int maxCandidate = sourceSize - targetSize;
if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
(source instanceof RandomAccess&&target instanceof RandomAccess)) {
nextCand:for (int candidate = 0; candidate <= maxCandidate; candidate++) {
for (int i=0, j=candidate; i
continue nextCand; // 元素失配,跳到外部循环
return candidate; // All elements of candidate matched target
}
} else { // Iterator version of above algorithm
ListIterator> si = source.listIterator();
nextCand:for (int candidate = 0; candidate <= maxCandidate; candidate++) {
ListIterator> ti = target.listIterator();
for (int i=0; i
// 回溯指针,然后跳到外部循环继续执行
for (int j=0; j si.previous();
continue nextCand;
}
}
return candidate;
}
}
return -1; //没有找到匹配的子串返回-1
}
/**
* 如果有一个或多个字串,返回最后一个出现的子串的第一个元素的索引
*/
public static int lastIndexOfSubList(List> source, List> target) {
int sourceSize = source.size();
int targetSize = target.size();
int maxCandidate = sourceSize - targetSize;
if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
source instanceof RandomAccess) { // Index access version
nextCand:for (int candidate = maxCandidate; candidate >= 0; candidate--) {
for (int i=0, j=candidate; i
continue nextCand; // Element mismatch, try next cand
return candidate; // All elements of candidate matched target
}
} else { // Iterator version of above algorithm
if (maxCandidate < 0)
return -1;
ListIterator> si = source.listIterator(maxCandidate);
nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) {
ListIterator> ti = target.listIterator();
for (int i=0; i
if (candidate != 0) {
// Back up source iterator to next candidate
for (int j=0; j<=i+1; j++)
si.previous();
}
continue nextCand;
}
}
return candidate;
}
}
return -1; // No candidate matched the target
}
// Unmodifiable Wrappers
/**
*
* 返回一个关于指定集合的不可修改的视图。
* 任何试图修改该视图的操作都将抛出一个UnsupportedOperationException
*
* Collection返回的视图的equals方法不是调用底层集合的equals方法
* 而是继承了Object的equals方法。hashCode方法也是一样的。
* 因为Set和List的equals方法并不相同。
*/
public static
return new UnmodifiableCollection
}
static class UnmodifiableCollection
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 1820017752578914078L;
final Collection extends E> c;
UnmodifiableCollection(Collection extends E> c) {
if (c==null)
throw new NullPointerException();
this.c = c;
}
public int size() {return c.size();}
public boolean isEmpty() {return c.isEmpty();}
public boolean contains(Object o) {return c.contains(o);}
public Object[] toArray() {return c.toArray();}
public
public String toString() {return c.toString();}
public Iterator
return new Iterator
Iterator extends E> i = c.iterator();
public boolean hasNext() {return i.hasNext();}
public E next() {return i.next();}
public void remove() { //试图修改集合的操作都将抛出此异常
throw new UnsupportedOperationException();
}
};
}
public boolean add(E e){
throw new UnsupportedOperationException();
}
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
public boolean containsAll(Collection> coll) {
return c.containsAll(coll);
}
public boolean addAll(Collection extends E> coll) {
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection> coll) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection> coll) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}
}
/**
* 返回一个不可修改Set。
* 调用的是底层集合的equals方法
*/
public static
return new UnmodifiableSet
}
/**
* @serial include
*/
static class UnmodifiableSet
implements Set
private static final long serialVersionUID = -9215047833775013803L;
UnmodifiableSet(Set extends E> s) {super(s);}
public boolean equals(Object o) {return o == this || c.equals(o);}
public int hashCode() {return c.hashCode();}
}
/**
* 返回一个不可修改的Sort Set
*/
public static
return new UnmodifiableSortedSet
}
static class UnmodifiableSortedSet
extends UnmodifiableSet
implements SortedSet
private static final long serialVersionUID = -4929149591599911165L;
private final SortedSet
UnmodifiableSortedSet(SortedSet
public Comparator super E> comparator() {return ss.comparator();}
public SortedSet
return new UnmodifiableSortedSet
}
public SortedSet
return new UnmodifiableSortedSet
}
public SortedSet
return new UnmodifiableSortedSet
}
public E first() {return ss.first();}
public E last() {return ss.last();}
}
/**
* 返回一个 不可修改的List
* 如果原List实现了RandomAccess接口,返回的List也将实现此接口
*/
public static
return (list instanceof RandomAccess ?
new UnmodifiableRandomAccessList
new UnmodifiableList
}
static class UnmodifiableList
implements List
static final long serialVersionUID = -283967356065247728L;
final List extends E> list;
UnmodifiableList(List extends E> list) {
super(list);
this.list = list;
}
public boolean equals(Object o) {return o == this || list.equals(o);}
public int hashCode() {return list.hashCode();}
public E get(int index) {return list.get(index);}
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
public int indexOf(Object o) {return list.indexOf(o);}
public int lastIndexOf(Object o) {return list.lastIndexOf(o);}
public boolean addAll(int index, Collection extends E> c) {
throw new UnsupportedOperationException();
}
public ListIterator
public ListIterator
return new ListIterator
ListIterator extends E> i = list.listIterator(index);
public boolean hasNext() {return i.hasNext();}
public E next() {return i.next();}
public boolean hasPrevious() {return i.hasPrevious();}
public E previous() {return i.previous();}
public int nextIndex() {return i.nextIndex();}
public int previousIndex() {return i.previousIndex();}
public void remove() {
throw new UnsupportedOperationException();
}
public void set(E e) {
throw new UnsupportedOperationException();
}
public void add(E e) {
throw new UnsupportedOperationException();
}
};
}
public List
return new UnmodifiableList
}
/**
* UnmodifiableRandomAccessList instances are serialized as
* UnmodifiableList instances to allow them to be deserialized
* in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
* This method inverts the transformation. As a beneficial
* side-effect, it also grafts the RandomAccess marker onto
* UnmodifiableList instances that were serialized in pre-1.4 JREs.
*
* Note: Unfortunately, UnmodifiableRandomAccessList instances
* serialized in 1.4.1 and deserialized in 1.4 will become
* UnmodifiableList instances, as this method was missing in 1.4.
* 这个,自己看吧...
*/
private Object readResolve() {
return (list instanceof RandomAccess
? new UnmodifiableRandomAccessList
: this);
}
}
static class UnmodifiableRandomAccessList
implements RandomAccess{
UnmodifiableRandomAccessList(List extends E> list) {
super(list);
}
public List
return new UnmodifiableRandomAccessList
list.subList(fromIndex, toIndex));
}
private static final long serialVersionUID = -2542308836966382001L;
/**
* Allows instances to be deserialized in pre-1.4 JREs (which do
* not have UnmodifiableRandomAccessList). UnmodifiableList has
* a readResolve method that inverts this transformation upon
* deserialization.
*/
private Object writeReplace() {
return new UnmodifiableList
}
}
/**
* 返回一个不可修改的map
*/
public static
return new UnmodifiableMap
}
private static class UnmodifiableMap
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = -1034234728574286014L;
private final Map extends K, ? extends V> m;
UnmodifiableMap(Map extends K, ? extends V> m) {
if (m==null)
throw new NullPointerException();
this.m = m;
}
public int size() {return m.size();}
public boolean isEmpty() {return m.isEmpty();}
public boolean containsKey(Object key) {return m.containsKey(key);}
public boolean containsValue(Object val) {return m.containsValue(val);}
public V get(Object key) {return m.get(key);}
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
public V remove(Object key) {
throw new UnsupportedOperationException();
}
public void putAll(Map extends K, ? extends V> m) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}
private transient Set
private transient Set
private transient Collection
//返回的key集也是不可修改的
public Set
if (keySet==null)
keySet = unmodifiableSet(m.keySet());
return keySet;
}
//EntrySet被重新进行包装
public Set
if (entrySet==null)
entrySet = new UnmodifiableEntrySet
return entrySet;
}
public Collection
if (values==null)
values = unmodifiableCollection(m.values());
return values;
}
public boolean equals(Object o) {return o == this || m.equals(o);}
public int hashCode() {return m.hashCode();}
public String toString() {return m.toString();}
/**
*
* 需要重新包装返回的EntrySet对象
*/
static class UnmodifiableEntrySet
private static final long serialVersionUID = 7854390611657943733L;
UnmodifiableEntrySet(Set extends Map.Entry extends K, ? extends V>> s) {
super((Set)s);
}
public Iterator
return new Iterator
//父类UnmodifiableColletion的c
Iterator extends Map.Entry extends K, ? extends V>> i = c.iterator();
public boolean hasNext() {
return i.hasNext();
}
public Map.Entry
return new UnmodifiableEntry
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public Object[] toArray() {
Object[] a = c.toArray();
for (int i=0; i
return a;
}
public
Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
for (int i=0; i
if (arr.length > a.length)
return (T[])arr;
System.arraycopy(arr, 0, a, 0, arr.length);
if (a.length > arr.length)
a[arr.length] = null;
return a;
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
return c.contains(new UnmodifiableEntry
}
public boolean containsAll(Collection> coll) {
Iterator> e = coll.iterator();
while (e.hasNext())
if (!contains(e.next())) // Invokes safe contains() above
return false;
return true;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Set s = (Set) o;
if (s.size() != c.size())
return false;
return containsAll(s); // Invokes safe containsAll() above
}
/**
* 重新包装Entry。
*/
private static class UnmodifiableEntry
private Map.Entry extends K, ? extends V> e;
UnmodifiableEntry(Map.Entry extends K, ? extends V> e) {this.e = e;}
public K getKey() {return e.getKey();}
public V getValue() {return e.getValue();}
public V setValue(V value) { //调用set方法将抛出一个异常
throw new UnsupportedOperationException();
}
public int hashCode() {return e.hashCode();}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry t = (Map.Entry)o;
return eq(e.getKey(), t.getKey()) &&
eq(e.getValue(), t.getValue());
}
public String toString() {return e.toString();}
}
}
}
/**
* 返回一个不可修改的SortedMap
*/
public static
return new UnmodifiableSortedMap
}
static class UnmodifiableSortedMap
implements SortedMap
private static final long serialVersionUID = -8806743815996713206L;
private final SortedMap
UnmodifiableSortedMap(SortedMap
public Comparator super K> comparator() {return sm.comparator();}
public SortedMap
return new UnmodifiableSortedMap
}
public SortedMap
return new UnmodifiableSortedMap
}
public SortedMap
return new UnmodifiableSortedMap
}
public K firstKey() {return sm.firstKey();}
public K lastKey() {return sm.lastKey();}
}
// 同步包装
/**
*
* 返回一个线程安全的集合
* 但是当用户遍历此集合时,需要手动进行同步
* Collection c = Collections.synchronizedCollection(myCollection);
* ...
* synchronized(c) {
* Iterator i = c.iterator(); // Must be in the synchronized block
* while (i.hasNext())
* foo(i.next());
* }
*
*/
public static
return new SynchronizedCollection
}
static
return new SynchronizedCollection
}
/**
* @serial include
*/
static class SynchronizedCollection
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 3053995032091335093L;
final Collection
final Object mutex; // 需要同步的对象
SynchronizedCollection(Collection
if (c==null)
throw new NullPointerException();
this.c = c;
mutex = this;
}
SynchronizedCollection(Collection
this.c = c;
this.mutex = mutex;
}
public int size() {
synchronized(mutex) {return c.size();}
}
public boolean isEmpty() {
synchronized(mutex) {return c.isEmpty();}
}
public boolean contains(Object o) {
synchronized(mutex) {return c.contains(o);}
}
public Object[] toArray() {
synchronized(mutex) {return c.toArray();}
}
public
synchronized(mutex) {return c.toArray(a);}
}
public Iterator
return c.iterator(); // 必须用户自己手动同步
}
public boolean add(E e) {
synchronized(mutex) {return c.add(e);}
}
public boolean remove(Object o) {
synchronized(mutex) {return c.remove(o);}
}
public boolean containsAll(Collection> coll) {
synchronized(mutex) {return c.containsAll(coll);}
}
public boolean addAll(Collection extends E> coll) {
synchronized(mutex) {return c.addAll(coll);}
}
public boolean removeAll(Collection> coll) {
synchronized(mutex) {return c.removeAll(coll);}
}
public boolean retainAll(Collection> coll) {
synchronized(mutex) {return c.retainAll(coll);}
}
public void clear() {
synchronized(mutex) {c.clear();}
}
public String toString() {
synchronized(mutex) {return c.toString();}
}
private void writeObject(ObjectOutputStream s) throws IOException {
synchronized(mutex) {s.defaultWriteObject();}
}
}
/**
* 返回一个线程安全的Set
*/
public static
return new SynchronizedSet
}
static
return new SynchronizedSet
}
/**
* @serial include
*/
static class SynchronizedSet
private static final long serialVersionUID = 487447009682186044L;
SynchronizedSet(Set
super(s);
}
SynchronizedSet(Set
super(s, mutex);
}
public boolean equals(Object o) {
synchronized(mutex) {return c.equals(o);}
}
public int hashCode() {
synchronized(mutex) {return c.hashCode();}
}
}
/**
* 返回一个线程安全的SortedSet
*/
public static
return new SynchronizedSortedSet
}
/**
* @serial include
*/
static class SynchronizedSortedSet
private static final long serialVersionUID = 8695801310862127406L;
final private SortedSet
SynchronizedSortedSet(SortedSet
super(s);
ss = s;
}
SynchronizedSortedSet(SortedSet
super(s, mutex);
ss = s;
}
public Comparator super E> comparator() {
synchronized(mutex) {return ss.comparator();}
}
public SortedSet
synchronized(mutex) {
return new SynchronizedSortedSet
ss.subSet(fromElement, toElement), mutex);
}
}
public SortedSet
synchronized(mutex) {
return new SynchronizedSortedSet
}
}
public SortedSet
synchronized(mutex) {
return new SynchronizedSortedSet
}
}
public E first() {
synchronized(mutex) {return ss.first();}
}
public E last() {
synchronized(mutex) {return ss.last();}
}
}
/**
* 返回一个线程安全的List,
* 如果List是基于随机访问的,返回的List同样实现了RandomAccess接口
*/
public static
return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList
new SynchronizedList
}
static
return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList
new SynchronizedList
}
/**
* @serial include
*/
static class SynchronizedList
static final long serialVersionUID = -7754090372962971524L;
final List
SynchronizedList(List
super(list);
this.list = list;
}
SynchronizedList(List
super(list, mutex);
this.list = list;
}
public boolean equals(Object o) {
synchronized(mutex) {return list.equals(o);}
}
public int hashCode() {
synchronized(mutex) {return list.hashCode();}
}
public E get(int index) {
synchronized(mutex) {return list.get(index);}
}
public E set(int index, E element) {
synchronized(mutex) {return list.set(index, element);}
}
public void add(int index, E element) {
synchronized(mutex) {list.add(index, element);}
}
public E remove(int index) {
synchronized(mutex) {return list.remove(index);}
}
public int indexOf(Object o) {
synchronized(mutex) {return list.indexOf(o);}
}
public int lastIndexOf(Object o) {
synchronized(mutex) {return list.lastIndexOf(o);}
}
public boolean addAll(int index, Collection extends E> c) {
synchronized(mutex) {return list.addAll(index, c);}
}
public ListIterator
return list.listIterator(); // Must be manually synched by user
}
public ListIterator
return list.listIterator(index); // Must be manually synched by user
}
public List
synchronized(mutex) {
return new SynchronizedList
mutex);
}
}
private Object readResolve() {
return (list instanceof RandomAccess
? new SynchronizedRandomAccessList
: this);
}
}
/**
* @serial include
*/
static class SynchronizedRandomAccessList
implements RandomAccess {
SynchronizedRandomAccessList(List
super(list);
}
SynchronizedRandomAccessList(List
super(list, mutex);
}
public List
synchronized(mutex) {
return new SynchronizedRandomAccessList
list.subList(fromIndex, toIndex), mutex);
}
}
static final long serialVersionUID = 1530674583602358482L;
private Object writeReplace() {
return new SynchronizedList
}
}
/**
* 返回一个线程安全的map
*/
public static
return new SynchronizedMap
}
/**
* @serial include
*/
private static class SynchronizedMap
implements Map
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 1978198479659022715L;
private final Map
final Object mutex; // Object on which to synchronize
SynchronizedMap(Map
if (m==null)
throw new NullPointerException();
this.m = m;
mutex = this;
}
SynchronizedMap(Map
this.m = m;
this.mutex = mutex;
}
public int size() {
synchronized(mutex) {return m.size();}
}
public boolean isEmpty(){
synchronized(mutex) {return m.isEmpty();}
}
public boolean containsKey(Object key) {
synchronized(mutex) {return m.containsKey(key);}
}
public boolean containsValue(Object value){
synchronized(mutex) {return m.containsValue(value);}
}
public V get(Object key) {
synchronized(mutex) {return m.get(key);}
}
public V put(K key, V value) {
synchronized(mutex) {return m.put(key, value);}
}
public V remove(Object key) {
synchronized(mutex) {return m.remove(key);}
}
public void putAll(Map extends K, ? extends V> map) {
synchronized(mutex) {m.putAll(map);}
}
public void clear() {
synchronized(mutex) {m.clear();}
}
private transient Set
private transient Set
private transient Collection
public Set
synchronized(mutex) {
if (keySet==null)
keySet = new SynchronizedSet
return keySet;
}
}
public Set
synchronized(mutex) {
if (entrySet==null)
entrySet = new SynchronizedSet
return entrySet;
}
}
public Collection
synchronized(mutex) {
if (values==null)
values = new SynchronizedCollection
return values;
}
}
public boolean equals(Object o) {
synchronized(mutex) {return m.equals(o);}
}
public int hashCode() {
synchronized(mutex) {return m.hashCode();}
}
public String toString() {
synchronized(mutex) {return m.toString();}
}
private void writeObject(ObjectOutputStream s) throws IOException {
synchronized(mutex) {s.defaultWriteObject();}
}
}
/**
* 返回一个线程安全的SortedSet
*/
public static
return new SynchronizedSortedMap
}
/**
* @serial include
*/
static class SynchronizedSortedMap
extends SynchronizedMap
implements SortedMap
{
private static final long serialVersionUID = -8798146769416483793L;
private final SortedMap
SynchronizedSortedMap(SortedMap
super(m);
sm = m;
}
SynchronizedSortedMap(SortedMap
super(m, mutex);
sm = m;
}
public Comparator super K> comparator() {
synchronized(mutex) {return sm.comparator();}
}
public SortedMap
synchronized(mutex) {
return new SynchronizedSortedMap
sm.subMap(fromKey, toKey), mutex);
}
}
public SortedMap
synchronized(mutex) {
return new SynchronizedSortedMap
}
}
public SortedMap
synchronized(mutex) {
return new SynchronizedSortedMap
}
}
public K firstKey() {
synchronized(mutex) {return sm.firstKey();}
}
public K lastKey() {
synchronized(mutex) {return sm.lastKey();}
}
}
// Dynamically typesafe collection wrappers
/**
*
* 返回一个动态的类型安全的集合。任何试图插入错误类型的元素的操作将立刻抛出
* ClassCastException
* 动态类型安全视图的一个主要作用是用作debug调试,
* 因为它能正确反映出出错的位置。
* 例如:ArrayList