上面的文章比较了Hashtable和HashMap的区别,今天看了另外一对相似关系的集合对象Vector和ArrayList
Hashtable是线程安全的key-value数据结构,HashMap是线程不安全的key-value数据结构
Vector是线程安全的List,ArrayList是线程不安全的List。
Vector在类注释里面就标注了这段话
As of the Java 2 platform v1.2, this class was retrofitted to
* implement the List interface, making it a member of the
* Java Collections Framework. Unlike the new collection
* implementations, Vector is synchronized. If a thread-safe
* implementation is not needed, it is recommended to use
* ArrayList in place of Vector.
在java1.2的时候Vector被重新改造过,继承了List,成为java collections 框架的一部分,在不要求线程安全的情况下,推荐用ArrayList 替代 Vector,所以大家在使用的时候要区分是否存在线程并发的情况。
仔细看源码为什么Vector会是线程安全的,跟Hashtable一样,Vector在操作方法上加了synchronized的关键字
/**
* Appends the specified element to the end of this Vector.
*
* @param e element to be appended to this Vector
* @return {@code true} (as specified by {@link Collection#add})
* @since 1.2
*/
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* Returns the element at the specified position in this Vector.
*
* @param index index of the element to return
* @return object at the specified index
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
* @since 1.2
*/
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
上面的方法就是简单的get/set方法。我们看到都加了synchronied的关键字