码迷,mamicode.com
首页 > 其他好文 > 详细

Vector源码分析

时间:2016-11-04 16:31:43      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:解析   ret   容量   current   修改   ref   快速   exception   asm   

在之前文章ArrayList源码解析(http://www.cnblogs.com/leskang/p/6019887.html)中分析了一下 ArrayList的源码和一些重要方法,现在对比 ArrayList,总结一下 Vector和 ArrayList的不同
 
构造方法
其实两者在很多地方都是一样的,然而在构造方法上面, Vector比 ArrayList多了一个方法:
public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

 

主要是因为 ArrayList中没有 capacityIncrement这个变量, vector的这个构造方法,不仅能够指定初始化容量,还能指定当容量不够时,容量自增的大小。下面看扩容方法.
 
扩容策略
在 ArrayList中,扩容的时候一般都是增加0.5倍左右,而在 Vector中,如果指定了这个 capacityIncrement,就会在原来容量的基础上增加 capacityIncrement;如果没有指定,则增加一倍容量。
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

 

除了这一点,其它和 ArrayList一模一样。
 
同步
众所周知, Vector是同步的而 ArrayList不是, Vector在一些必要的方法上都加了 synchronized关键字,但是这也会加大系统开销。
Enumeration
Vector中有一个 elements()方法用来返回一个 Enumeration,以匿名内部类的方式实现的:
public Enumeration<E> elements() {
        return new Enumeration<E>() {
            int count = 0;
            public boolean hasMoreElements() {
                return count < elementCount;
            }
            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

 

Enumeration接口和 Iterator类似,产生先于Iterator,都用作于对集合进行迭代,不过没有删除功能,已经被 Iterator取代。还有Iterator 是 Fast-Fail(快速失效)的,但 Enumeration不是,这一点很重要。
Fast-Fail快速失效机制尽早抛出错误对程序来说提高了程序的反应速率
fail-fast
“快速失败”也就是fail-fast,它是Java集合的一种错误检测机制。当多个线程对集合进行结构上的改变的操作时,有可能会产生fail-fast机制。记住是有可能,而不是一定。例如:假设存在两个线程(线程1、线程2),线程1通过Iterator在遍历集合A中的元素,在某个时候线程2修改了集合A的结构(是结构上面的修改,而不是简单的修改集合元素的内容),那么这个时候程序就会抛出 ConcurrentModificationException 异常,从而产生fail-fast机制。
注意,迭代器的快速失败行为不能得到保证,一般来说,存在非同步的并发修改时,不可能作出任何坚决的保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。因此,编写依赖于此异常的程序的做法是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测程序错误。
 

Vector源码分析

标签:解析   ret   容量   current   修改   ref   快速   exception   asm   

原文地址:http://www.cnblogs.com/leskang/p/6030459.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!