Collections工具类里的
Collections.synchronizedList
public static <T> List<T> synchronizedList(List<T> list) {
return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList<T>(list) :
new SynchronizedList<T>(list));
}
##仅仅是通过判断是否实现RandomAccess接口,而返回不同的SynchronizedList(内部)类,
##RandomAccess foreach较快, iterator较慢,差别不明显(如i5上,本人测试,一个ArrayList,90w个object, foreach出来是6多ms, iterator出来7ms)
##SequenceAccess foreach较慢,iterator较快.差别非常明显. (如i5上,本人测试,一个LinkedList,10w个object, foreach出来是200多ms, iterator出来仅4ms)
LinkedList的get(n) 方法. 源码里写得也有点妙,一不留意 确实是个坑. (这是SequenceAccess 的foreach 慢的原因)
private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}