zoukankan      html  css  js  c++  java
  • Java中Vector与ArrayList的差别具体解释

    首先看这两类都实现List接口,而List接口一共同拥有三个实现类。各自是ArrayList、Vector和LinkedList。List用于存放多个元素,可以维护元素的次序,而且同意元素的反复。


    3个详细实现类的相关差别例如以下:

    1.ArrayList是最经常使用的List实现类,内部是通过数组实现的,它同意对元素进行高速随机訪问。数组的缺点是每一个元素之间不能有间隔,当数组大小不满足时须要添加存储能力。就要讲已经有数组的数据拷贝到新的存储空间中。当从ArrayList的中间位置插入或者删除元素时,须要对数组进行复制、移动、代价比較高。

    因此,它适合随机查找和遍历,不适合插入和删除。

    2.Vector与ArrayList一样,也是通过数组实现的,不同的是它支持线程的同步,即某一时刻仅仅有一个线程可以写Vector。避免多线程同一时候写而引起的不一致性,但实现同步须要非常高的花费,因此。訪问它比訪问ArrayList慢。

    3.LinkedList是用链表结构存储数据的,非常适合数据的动态插入和删除,随机訪问和遍历速度比較慢。另外,他还提供了List接口中未定义的方法,专门用于操作表头和表尾元素。能够当作堆栈、队列和双向队列使用。

    查看Java源码。发现当数组的大小不够的时候,须要又一次建立数组,然后将元素复制到新的数组内,ArrayList和Vector的扩展数组的大小不同。


    ArrayList中:

    复制代码 代码例如以下:

    public boolean add(E e) {
         ensureCapacity(size + 1);  // 添加元素。推断是否可以容纳。不能的话就要新建数组
         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);
         }
     }

    Vector中:
    复制代码 代码例如以下:

    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和Vector差别例如以下:
    1.ArrayList在内存不够时默认是扩展50% + 1个,Vector是默认扩展1倍。


    2.Vector提供indexOf(obj, start)接口,ArrayList没有。
    3.Vector属于线程安全级别的。可是大多数情况下不使用Vector,由于线程安全须要更大的系统开销。

  • 相关阅读:
    leetcode 122. Best Time to Buy and Sell Stock II
    leetcode 121. Best Time to Buy and Sell Stock
    python 集合(set)和字典(dictionary)的用法解析
    leetcode 53. Maximum Subarray
    leetcode 202. Happy Number
    leetcode 136.Single Number
    leetcode 703. Kth Largest Element in a Stream & c++ priority_queue & minHeap/maxHeap
    [leetcode]1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree
    正则表达式
    十种排序算法
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6791402.html
Copyright © 2011-2022 走看看