ArrayList&LinkedList&Vector(penguin)

=========================================================

ArrayList是实现了基于动态数组的数据结构:(源码)

transient Object[] elementData;

LinkedList基于链表的数据结构:(源码

transient Node<E> first;

transient Node<E> last;

============================================================

ArrayList&LinkedList都实现了List接口

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{

}

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{

}

==============================================================

ArrayList添加元素的过程:

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // 确保对象数组elementData有足够的容量,可以将新加入的元素e加进去

        elementData[size++] = e;//加入新元素e,size加1

        return true;

}

    /**
     * 确保数组的容量足够存放新加入的元素,若不够,要扩容
     */
    public void ensureCapacity(int minCapacity) {
        modCount++;
        int oldCapacity = elementData.length;//获取数组大小(即数组的容量)
        //当数组满了,又有新元素加入的时候,执行扩容逻辑
        if (minCapacity > oldCapacity) {
            Object oldData[] = elementData;
            int newCapacity = (oldCapacity * 3) / 2 + 1;//新容量为旧容量的1.5倍+1
            if (newCapacity < minCapacity)//如果扩容后的新容量还是没有传入的所需的最小容量大或等于(主要发生在addAll(Collection<? extends E> c)中)
                newCapacity = minCapacity;//新容量设为最小容量
            elementData = Arrays.copyOf(elementData, newCapacity);//复制新容量
        }
    }

LinkedList添加元素的过程:

//Appends the specified element to the end of this list.
 2     public boolean add(E e) {
 3         linkLast(e);
 4         return true;
 5     }
 6     /**
 7      * Links e as last element.
 8      */
 9     void linkLast(E e) {
10         final Node<E> l = last;
11         final Node<E> newNode = new Node<>(l, e, null);
12         last = newNode;
13         if (l == null)
14             first = newNode;
15         else
16             l.next = newNode;
17         size++;
18         modCount++;
19     }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值