Vector

作者: 赵呆一 | 来源:发表于2020-07-03 15:20 被阅读0次

    前言

    这个和ArrayList百分之90感觉都是类似的只是这个是线程安全的 ArrayList 不是线程安全的

    代码

    分析Vector主要从下面几个方面来分析器
    1.vector增长的策略是什么

    1. vector添加一个元素 和删除一个元素跟ArrayList差别
      /**
         * Constructs an empty vector with the specified initial capacity and
         * capacity increment.
         *
         * @param   initialCapacity     the initial capacity of the vector
         * @param   capacityIncrement   the amount by which the capacity is
         *                              increased when the vector overflows
         * @throws IllegalArgumentException if the specified initial capacity
         *         is negative
         */
        public Vector(int initialCapacity, int capacityIncrement) {
            super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
            this.elementData = new Object[initialCapacity];
            this.capacityIncrement = capacityIncrement;
        }
    

    初始化指定的大小就是10 这跟ArrayList很像 只不过ArrayList一开始为零下次再扩展的时候进行一次判断

    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);
    }
    
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    

    这里是真正扩容的方法 ArrayList是位移的方式 这里是判断

       /**
         * 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;
        }
    

    添加时候有用锁关键字 所以线程安全

    相关文章

      网友评论

          本文标题:Vector

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