Java集合-List

本文详细解析了Java中的ArrayList和LinkedList数据结构,包括它们的属性、关键方法如添加、删除、查找以及容量管理机制,展示了这两种集合类的核心操作原理。
摘要由CSDN通过智能技术生成

ArrayList

属性

Object[] elementData; // 元素数组
int size; // 元素个数
Object[] EMPTY_ELEMENTDATA = {}; // initialCapacity=0
Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; // 未指定initialCapacity
int DEFAULT_CAPACITY = 10;
int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // 防止对象size超JVM限制
普通方法

// 遍历elementData:从0开始,返回第一个匹配项(equals);o是null,返回第一个null索引;命中失败,返回-1
public int indexOf(Object o)
// 从size-1开始
public int lastIndexOf(Object o)
// indexOf(o) >= 0
public boolean contains(Object o)
// 更新,返旧;index不对抛异常
public E set(int index, E element)
// modCound++,elementData置空,size归0
public void clear()
// 序列化
private void readObject(java.io.ObjectInputStream s)
private void writeObject(java.io.ObjectOutputStream s)
添加元素

// 默认末尾添加
public boolean add(E e) {
    ensureCapacityInternal(size + 1);
    elementData[size++] = e;
    return true;
}

// 索引添加
public void add(int index, E element) {
    rangeCheckForAdd(index); // 可以等于size
    ensureCapacityInternal(size + 1);
    System.arraycopy(elementData, index, elementData, index + 1, size - index);
    elementData[index] = element;
    size++;
}

// 批量末尾
public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;
    return numNew != 0;
}

// 批量索引
public boolean addAll(int index, Collection<? extends E> c) {
    rangeCheckForAdd(index);

    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);

    int numMoved = size - index;
    if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew, numMoved);

    System.arraycopy(a, 0, elementData, index, numNew);
    size += numNew;
    return numNew != 0;
}
扩容
  • 扩容系数:1.5

// add,addAll,readObject调用
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    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)
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}

// 外部调用
public void ensureCapacity(int minCapacity) {
    int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;
    if (minCapacity > minExpand) {
        ensureExplicitCapacity(minCapacity);
    }
}

// 手动缩减elementData至size,采用Arrays.copyOf
public void trimToSize()
查找

// 灰常灰常快,对泛型做了主动转型
public E get(int index) {
    rangeCheck(index); // 竟然没查index < 0,不过也无所谓,后面还是会报错
    return elementData(index);
}

@SuppressWarnings("unchecked")
E elementData(int index) {
        return (E) elementData[index];
}
删除
  • 不调整elementData,trimToSize可手动压缩

public E remove(int index) {
    rangeCheck(index);

    modCount++;
    E oldValue = elementData(index);
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index, numMoved);
    elementData[--size] = null;
    return oldValue;
}

public boolean remove(Object o) {
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}

private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index, numMoved);
    elementData[--size] = null;
}

// 集合碰撞删除
public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}

// 集合碰撞保留
public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, true);
}

private boolean batchRemove(Collection<?> c, boolean complement)
    ...
    // false,碰撞移除;true,碰撞保留
    if (c.contains(elementData[r]) == complement)   
       elementData[w++] = elementData[r];
    // 不出异常的话,只要把w后面剩余的全部置空即可

其它方法

// 浅拷贝之外,需拷贝elementData,并将modCount置0
public Object clone() {
    try {
        ArrayList<?> v = (ArrayList<?>) super.clone();
        v.elementData = Arrays.copyOf(elementData, size);
        v.modCount = 0;
        return v;
    } catch (CloneNotSupportedException e) {
        throw new InternalError(e);
    }
}

public Object[] toArray() {
    return Arrays.copyOf(elementData, size);
}

@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
    if (a.length < size)
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

LinkedList - 双向链表

属性

int size = 0; // why transient
Node<E> first;
Node<E> last;
int modCount = 0;
Node

private static class Node<E> {
    Node<E> prev;
    E item;
    Node<E> next;
    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}
普通方法

// 索引定位Node,根据index大小分前后
Node<E> node(int index) {
    // assert isElementIndex(index);
    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

public int indexOf(Object o) {
    int index = 0;
    if (o == null) {
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null)
                return index;
            index++;
        }
    } else {
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item))
                return index;
            index++;
        }
    }
    return -1;
}

public int lastIndexOf(Object o) {
    int index = size;
    if (o == null) {
        for (Node<E> x = last; x != null; x = x.prev) {
            index--;
            if (x.item == null)
                return index;
        }
    } else {
        for (Node<E> x = last; x != null; x = x.prev) {
            index--;
            if (o.equals(x.item))
                return index;
        }
    }
    return -1;
}

public boolean contains(Object o) {
    return indexOf(o) != -1;
}

public E set(int index, E element) {
    checkElementIndex(index);
    Node<E> x = node(index);
    E oldVal = x.item;
    x.item = element;
    return oldVal;
}

public void clear() {
    for (Node<E> x = first; x != null; ) {
        Node<E> next = x.next;
        x.item = null;
        x.next = null;
        x.prev = null;
        x = next;
    }
    first = last = null;
    size = 0;
    modCount++;
}

// 序列化
private void readObject(java.io.ObjectInputStream s)
private void writeObject(java.io.ObjectOutputStream s)
添加

// 默认末尾添加
public boolean add(E e) {
    linkLast(e);
    return true;
}

void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}

// 索引添加
 public void add(int index, E element) {
    checkPositionIndex(index);
    if (index == size)
        linkLast(element);
    else
        linkBefore(element, node(index));
}

void linkBefore(E e, Node<E> succ) {
    // assert succ != null;
    final Node<E> pred = succ.prev;
    final Node<E> newNode = new Node<>(pred, e, succ);
    succ.prev = newNode;
    if (pred == null)
        first = newNode;
    else
        pred.next = newNode;
    size++;
    modCount++;
}
public void addFirst(E e) // linkFirst
public void addLast(E e)  // linkLast
public boolean addAll(Collection<? extends E> c) // addAll(size, c)
public boolean addAll(int index, Collection<? extends E> c)
    checkPositionIndex(index);
    Object[] a = c.toArray();
    succ = node(index);
    // 遍历a,从succ开始,按序往后插入
    size += a.length;
    modCount++;   //mod只算一次
查找

public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}
public E getFirst() //first为空,抛NoSuchElementException
public E getLast()  //last为空,抛NoSuchElementException
删除

public E remove(int index) {
    checkElementIndex(index);
    return unlink(node(index));
}

public boolean remove(Object o) {
    if (o == null) {
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null) {
                unlink(x);
                return true;
            }
        }
    } else {
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item)) {
                unlink(x);
                return true;
            }
        }
    }
    return false;
}

E unlink(Node<E> x) // 将Node前后连在一起

public E removeFirst() // unlinkFirst
public E removeLast() // unlinkLast
private E unlinkFirst(Node<E> f)
private E unlinkLast(Node<E> l)
获取添加集锦

public E peek()                                // 返first,为空返null
public E peekFirst()                           // 返first,为空返null
public E peekLast()                            // 返last,为空返null

public E element()                             // 返first,为空抛异常

public E poll()                                // 删除返first,为空返null
public E pollFirst()                           // 删除返first,为空返null
public E pollLast()                            // 删除返last,为空返null

public E pop()                                 // 删除返first,为空抛异常
public E remove()                              // 删除返first,为空抛异常

public void push(E e)                          // linkFirst(e)

public boolean offer(E e)                      // linkLast(e)
public boolean offerFirst(E e)                 // linkFirst(e)
public boolean offerLast(E e)                  // linkLast(e)

public boolean removeFirstOccurrence(Object o) // 删除从first开始的第一匹配项
public boolean removeLastOccurrence(Object o)  // 删除从last开始的第一匹配项
其它方法

public Object clone() {
    LinkedList<E> clone = superClone();
    // Put clone into "virgin" state
    clone.first = clone.last = null;
    clone.size = 0;
    clone.modCount = 0;
    // Initialize clone with our elements
    for (Node<E> x = first; x != null; x = x.next)
        clone.add(x.item);
    return clone;
}

public Object[] toArray() {
    Object[] result = new Object[size];
    int i = 0;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;
    return result;
}

@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
    int i = 0;
    Object[] result = a;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;
    if (a.length > size)
        a[size] = null;
    return a;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eddy咸鱼

感谢大佬加鸡蛋~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值