《java基础》第4集-浅析Vector

8 篇文章 0 订阅

上面的文章比较了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的关键字

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值