本系列博文将着重分析util包中的相关数据结构:
一、总瞰
接口collection提供了大部分对于数据结构操作,例如:
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean retainAll(Collection<?> c);
void clear();
而AbstractCollection是实现了Collection接口的抽象类,利用泛型实现了Collection中的接口。
同时,List、Set、Queue三个接口继承于Collection接口,底下有分别有自己的实现类AbstractList、AbstractSet、AbstractQueue;这三个抽象实现类不仅实现了各自接口,同时统一继承于AbstractCollection抽象类。
二、List类族
List类族中主要有4个实现类,ArrayList、LinkedList、Vector、CopyOnWriteArrayList,其中最后一个是应对多线程的实现类,所以也从属于concurrent并发包中。下面针对ArrayList、LinkedList、Vector进行分析。
1、ArrayList和Vector
ArrayList和Vector类中都使用了Object[] 数组实现,查看源码可以发现,这两个类中无论是参数或是方法返回值,都大量使用了Object[]数组形式。形如:
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
两者几乎使用了相同的算法,唯一的区别是对于多线程的支持。Vector类中绝大部分方法都对做了线程同步,代码块、方法体均对多线程有支持。而ArrayList没有任何方法对线程进行支持。下面展示两个Vector的方法实现
public synchronized void copyInto(Object[] anArray) {
System.arraycopy(elementData, 0, anArray, 0, elementCount);
}
public synchronized void ensureCapacity(int minCapacity) {
if (minCapacity > 0) {
modCount++;
ensureCapacityHelper(minCapacity);
}
}
2、LinkedList
LinkedList使用了循环双向链表数据结构,一个数据表项总包含:前指针-元素-后指针,对于学习过数据结构中的双向链表应该对这个结构不会陌生。这种结构特点也使得LinkedList相较于ArrayList或Vector有不一样的使用场景和数据操作方式。下面从添加元素、删除、容量、遍历列表几个方法对比两类数据结构的特点。
1、添加元素:
ArrayList基于一个容量参数,当ArrayList的当前容量足够大时,add操作是非常高效的。只有当容量不足时,才需要进行扩容操作,进行大量的数组复制。
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
LinkedList的add 操作,基于将元素添加到队尾,使用链表结构不需要维护容量大小,但每次都需要去new一个Node对象,所以在频繁调用时,可能会有一定的性能影响。
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
性能测试:
ArrayList<Object> list=new ArrayList<Object>();
LinkedList<Object> list2=new LinkedList<Object>();
System.out.println(System.currentTimeMillis());
Object obj=new Object();
for(int i=0;i<10000000;i++)
{
list2.add(obj);
}
System.out.println(System.currentTimeMillis());
结果:循环添加1000w次
ArrayList耗时:224ms
LinkedList耗时:9876ms
2、添加元素到任意位置
由于ArrayLlist是基于数组实现的,所以当添加元素到指定位置时,不免会破坏原来的数组结构,使得该位置之后的所有元素从新排列。而此时,采用链表结构的LinkedList便体现出来优势。
测试:
for(int i=0;i<10000000;i++)
{
list.add(0,obj);
}
结果:循环添加1000w次
ArrayList耗时:打了个水-上了个厕所-回来还没走完
LinkedList耗时:10038ms
3、删除任意位置元素
ArrayList:越靠前,数组重组造成的开销越大,越往后,开销越小。LinkedList是双向链表,所以在查找删除元素位置是,如果靠前,从前往后找,如果位置靠后,则从后往前,效率都相对较高;如果删除的元素恰好在中间位置,几乎要遍历半个List集合,如果数据很大时,开销会比较大。
测试:
ArrayList<Object> list=new ArrayList<Object>();
LinkedList<Object> list2=new LinkedList<Object>();
System.out.println(System.currentTimeMillis());
System.out.println(list.size());
while(list.size()>0)
{
list.remove(0);//从前往后删
list.remove(list.size()>>1);//从中间删除
list.remove(list.size()-1);//从后往前删
}
结果:List有10w条数据
ArrayList:6000ms(前)、3000(中间)、20(尾)-数组重排开销依次减少,所以效率越来越高
LinkedList:18(前)、9000(中间)、20(尾)-头尾删除效率持恒,中间最耗时
4、遍历表
JDK1.5之后,遍历列表主要方式有:forEach、迭代器、 for循环,依次对这三种方式进行测试:
for(String s:list)
{
tmp=s;
}
System.out.println("forEach:"+(System.currentTimeMillis()-start));
//迭代器
for(Iterable<String> it=list.iterator();it.hasNext();)
{
tmp=it.next();
}
System.out.println("forEach:"+(System.currentTimeMillis()-start));
//for循环
for(int i=0;i<list.size();i++)
{
tmp=list.get(i);
}
结果:list中有10w条数据,遍历结果如下:
ArrayList:63ms(ForEach)、47(迭代器)、31(for)
LinkedList:63ms(ForEach)、47(迭代器)、无限大--随机访问LinkedList,每会进行一次遍历表的操作,效率太低。
ForEach 和迭代器遍历方式基本持恒,对于随机访问,ArrayList速度是很快的,而LinkedList效率就不是打杯水-上个厕所可以等待的量级了。
三、总结:
对于这写常用数据结构,编程中使用非常频繁,随随便便就new一个集合却不知道针对当前场景这个集合类型是否适用,这是很可怕的。代码一行一行增加,最终导致系统访问速度过慢,还无法排查问题。千里之堤,毁于蚁穴。