美文网首页
Vector源代码阅读

Vector源代码阅读

作者: 梦想家图图图 | 来源:发表于2016-10-25 15:18 被阅读0次

    Vector实现了List,RandomAccess,Serializable,Cloneable接口,继承了AbstractList类,本质是数组类似ArrayList,所以Vector具有以下特性:**

    • 一个队列,支持相关的添加、删除、修改、遍历
    • Vector 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的,我们可以通过元素好快速访问元素。
    • 可以被克隆。
    • Vector所有的核心的操作方法都是线程安全的,方法中代码和ArrayList基本相同,但是方法有synchronized修饰。

    Vector的构造函数

    //默认构造大小为10的Vector
    public Vector() {
            this(10);   
        }
    
    //直接传入Vector进行创建新的Vector
    public Vector(Collection<? extends E> c) {
            elementData = c.toArray();
            elementCount = elementData.length;
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
        }
    
    // capacity是Vector的默认容量大小。当由于增加数据导致容量增加时,每次容量会增加一倍。
    Vector(int capacity)我们从这块代码可以看到:int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
    capacityIncrement : oldCapacity);
    
    // capacity是Vector的默认容量大小,capacityIncrement是每次Vector容量增加时的增量值。
    Vector(int capacity, int capacityIncrement)
    

    我们看下Vector和集合类之间的关系:

    Vector.png

    Vector支持的遍历方式:
    (01)迭代器访问

    Iterator<Integer> its = v.iterator();
            while(its.hasNext()) {
                System.out.println(its.next());
            }
    

    (02)for循环访问

    for(Integer id: v) {
                System.out.println(id);
     }
    

    (03)根据索引访问

    for(int i=0;i<v.size();i++) {
                System.out.println(v.get(i));
            }
    

    (04)使用Emulation遍历

    Enumeration<Integer> es = v.elements();
            while(es.hasMoreElements()) {
                System.out.println(es.nextElement());
            }
    

    使用随机访问的方式效率是最高的。

    相关文章

      网友评论

          本文标题:Vector源代码阅读

          本文链接:https://www.haomeiwen.com/subject/kxvruttx.html