Vector和ArrayList这两个集合类的本质并没有太大的不同,它们都实现了List接口,而且底层都是基于Java数组来存储集合元素。
在ArrayList集合类的源代码中可以看到如下一行。
//采用elementData数组来保存集合元素
private transient Object[] elementData;
在Vector集合类的源代码中也可看到类似的一行。
//采用elementData数组来保存集合元素
protected Object[] elementData;
从上面代码可以看出,ArrayList使用 transient 修饰了 elementData 数组。这保证系统序列化ArrayList对象时不会直接序列号elementData数组,而是通过ArrayList提高的writeObject、readObject方法来实现定制序列化;但对于Vector而言,它没有使用transient修饰elementData数组,而且Vector只提供了一个writeObject方法,并未完全实现定制序列化。
从序列化机制的角度来看,ArrayList的实现比Vector的实现更安全。除此之外,Vector其实就是ArrayList的线程安全版本,ArrayList和Vector绝大部分方法的实现都是相同的,只是Vector的方法增加了 synchronized修饰。
下面先来看ArrayList中的add(int index, E element)方法的源代码
public void add(int index, E element) {
//如果添加位置大于集合长度或者小于0,抛出异常
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+<

ArrayList和Vector都是Java中实现List接口的集合类,基于数组存储元素。ArrayList使用transient修饰elementData,提供更安全的序列化机制。Vector是线程安全的,但性能较低,其add方法和扩容机制相比ArrayList多了synchronized,且允许指定容量增长步长(capacityIncrement)。总结来说,ArrayList适合非线程环境追求性能,Vector适合线程安全场景。
最低0.47元/天 解锁文章
957

被折叠的 条评论
为什么被折叠?



