首先,推荐大家使用ArrayList,了解这个差别,更多是为了应对面试。
两者的最大差异就是线程安全
ArrayList:线程不安全,但性能高
Vector:线程安全,但性能较低
我们如何得到一个类是线程安全或不安全的结论的?
从源码的角度来说,你大可以打开ArrayList和Vector的源码一对比,即可发现
ArrayList的部分源码:
public boolean add(E e) {ensureCapacityInternal(size + 1); // Increments modCount!!elementData[size++] = e;return true;}Vector的部分源码:
public synchronized boolean add(E e) {modCount++;ensureCapacityHelper(elementCount + 1);elementData[elementCount++] = e;return true;}大家看出差异了吗?
本文对比了ArrayList和Vector两种集合类的特性。ArrayList提供更高的性能但不具备线程安全性,而Vector则相反,它确保了线程安全但牺牲了一部分性能。通过对源码的分析,我们发现Vector通过synchronized关键字实现同步,这导致了其在多线程环境下操作的开销。
3583

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



