小白学集合之看ArrayList和LinkedList源码

List实现类【重要】

ArrayList:
底层是数据,查询快,增删慢
JDK1.2版本,运行效率快,线程不安全

LinkedList:
底层是链表,查询慢,增删快

Vector:

底层是数据,查询快,增删慢
JDK1.0版本,运行效率慢,线程安全

ArrayList

ArrayListDemo类是ArrayList的一些方法的使用。

package com.list;

import com.collection.Student;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

/**
 * ArrayList的使用
 * 存储结构是数组,查找快,增删慢
 */
public class ArrayListDemo {
     
    public static void main(String[] args) {
     
        ArrayList arrayList = new ArrayList<>();

        Student s1 = new Student("张三", 18);
        Student s2 = new Student("李四", 20);
        Student s3 = new Student("王二", 22);

        //添加元素
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        System.out.println("元素个数:"+arrayList.size());

        //删除
//        arrayList.remove(s1);
//        System.out.println("删除之后个数:"+arrayList.size());

        //元素遍历
        Iterator it = arrayList.iterator();
        while (it.hasNext()) {
     
            Student s =(Student) it.next();
            System.out.println("迭代器遍历:"+s.toString());
        }
        ListIterator listIterator = arrayList.listIterator();
        while (listIterator.hasNext()) {
     
            Student stu = (Student) listIterator.next();
            System.out.println("列表迭代器遍历:"+stu.toString());
        }

        //判断
        System.out.println("是否包含s1:" +arrayList.contains(s1));
        System.out.println("是否为空:"+arrayList.isEmpty());

        //查找
        System.out.println("s2的下标:"+arrayList.indexOf(s2));
    }
}

ArrarList源码分析【重点】

ArrayList实现了List接口,有序容器,就是存进去元素的顺序和存的顺序一致,允许null元素,底层是数组,除了未实现同步,其他和Vector大致相同。

每个ArrayList都有一个容量(capacity),表示数组的实际大小。当像容器添加元素的时候,如果容量不够,容器会自动扩容,

变量名:

DEFAULT_CAPACITY:默认容量

EMPTY_ELEMENTDATA:空元素数据

DEFAULTCAPACITY_EMPTY_ELEMENTDATA:默认容量空元素数据

elementData:元素数据

size:元素个数

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {
     };

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {
     };

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

构造函数

可以看到有3个构造函数,如果ArrayList arrayList = new ArrayList<>();创建一个对象,就会调用无参构造,生成一个容量为0的arryList集合。

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
     
        if (initialCapacity > 0) {
     
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
     
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
     
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
     
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
     
        Object[] a = c.toArray();
        if ((size = a.length) != 0) {
     
            if (c.getClass() == ArrayList.class) {
     
                elementData = a;
            } else {
     
                elementData = Arrays.copyOf(a, size, Object[].class);
            }
        } else {
     
            // replace with empty array.
            elementData = EMPTY_ELEMENTDATA;
        }
    }

add(E e) 方法

当添加第一个元素的时候,因为初始为0,所以执行:ensureCapacityInternal(1)

/**
 * Appends the specified element to the end of this list.
 *
 * @param e element to be appended to this list
 * @return true (as specified by {@link Collection#add})
 */
public boolean add(E e) {
     
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

自动扩容

每当向数组中添加元素的时候,都会先检查添加后元素个数是否超过数组容量,如果超出,进行扩容。扩容通过 ensureCapacity(int minCapacity)方法实现。

数组扩容的时候会将老数组中的元素复制一份到新的数组中,第一次扩容是从0到10,然后每次扩容大概是原容量的1.5倍。扩容代价很高,我们应尽量避免扩容。

    /**
     * Increases the capacity of this ArrayList instance, if
     * necessary, to ensure that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     *
     * @param   minCapacity   the desired minimum capacity
     */
    public void ensureCapacity(int minCapacity) {
     
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
     
            ensureExplicitCapacity(minCapacity);
        }
    }

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

    private void ensureCapacityInternal(int minCapacity) {
     
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private void ensureExplicitCapacity(int minCapacity) {
     
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
     
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        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;
    }

LinkedList源码分析【重点】

LinkedList底层是双向链表

变量名

size:链表大小

first:第一个节点

last:最后一个节点

    transient int size = 0;

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;

Node是私有内部类

    private static class Node<E> {
     
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
     
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

构造函数

    /**
     * Constructs an empty list.
     * 构造一个空列表。
     */
    public LinkedList() {
     
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {
     
        this();
        addAll(c);
    }

add(E)方法

    /**
     * Appends the specified element to the end of this list.
     * 将指定的元素追加到此列表的末尾。
     * 

This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ public boolean add(E e) { linkLast(e); return true; } /** * Links e as last element. * 将e链接为最后一个元素。 */ 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++; }

在ArrayList的中间插入或删除一个元素,那列表中该元素往后的元素都会后移;而在LinkedList的中间插入或删除一个元素的开销是固定的。

LinkedList不能随机访问。

你可能感兴趣的:(集合框架,java)