zoukankan      html  css  js  c++  java
  • Java中的Vector和ArrayList

    面试期间曾被问到,这里做个简单的总结。

    Vector和ArrayList都是List<E>接口的实现类,内部均通过数组实现,适合随机遍历查找,不适合中间插入和删除。

    通过Java的源码,可以窥视两者的不同。以add()方法为例:

    Vector:

    public synchronized boolean add(E e) {
        modCount++; // From AbstractList, count the Structural modifications
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
            return true;
        }
    
      /**
         * This implements the unsynchronized semantics of ensureCapacity.
         * Synchronized methods in this class can internally call this
         * method for ensuring capacity without incurring the cost of an
         * extra synchronization.
         *
         * @see #ensureCapacity(int)
         */
        private void ensureCapacityHelper(int minCapacity) {
        int oldCapacity = elementData.length;
        if (minCapacity > oldCapacity) {
            Object[] oldData = elementData;
            int newCapacity = (capacityIncrement > 0) ?
            (oldCapacity + capacityIncrement) : (oldCapacity * 2);
                if (newCapacity < minCapacity) {
            newCapacity = minCapacity;
            }
                elementData = Arrays.copyOf(elementData, newCapacity);
        }
        }

    ArrayList:

    public boolean add(E e) {
        ensureCapacity(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
        }
    
    public void ensureCapacity(int minCapacity) {
        modCount++;
        int oldCapacity = elementData.length;
        if (minCapacity > oldCapacity) {
            Object oldData[] = elementData;
            int newCapacity = (oldCapacity * 3)/2 + 1;
                if (newCapacity < minCapacity)
            newCapacity = minCapacity;
                // minCapacity is usually close to size, so this is a win:
                elementData = Arrays.copyOf(elementData, newCapacity);
        }
        }

    根据上述源码可知:

    1. Vector是线程安全,而ArrayList不是。所以在非多线程环境,应该选择ArrayList,避免线程安全的系统开销

    2. 当存储空间不够的时候,Vector扩展一倍(oldCapacity*2),而ArrayList扩展一半+1个((oldCapacity * 3)/2 + 1)。

  • 相关阅读:
    自动化:Appium运行成功,取得一个小的胜利
    调优案例1
    HTTP请求方式中8种请求方法(简单介绍)
    Java中基本类型和引用类型(简单介绍)
    @WebListener 注解方式实现监听(eclipse和idea)
    Git免密码提交
    在idea配置jetty和创建(包、文件)javaWeb以及Servlet简单实现
    emmet工具使用和技巧
    Markdown基本语法总结
    viewport原理和使用和设置移动端自适应的方法(移动适应电脑)
  • 原文地址:https://www.cnblogs.com/techyc/p/2956173.html
Copyright © 2011-2022 走看看