ArrayList

Array是什么,可以用来干什么?

ArrayList就是数组列表,主要用来装载数据,他的主要底层实现是 Object[] elenmentDate.

与它类似的是LinkedList,和LinkedList相比,它的查找和访问元素的速度较快,但新增,删除的速度较慢。

什么线程不安全还要使用他?

因为我们正常使用的场景中,都是用来查询的,不会涉及太多的增删。如果涉及频繁增删的,可以使用LinkedList,如果需要线程安全就使用Vecotr,这就是三者的区别,实际开发中ArrayList使用最多。

不存在一个集合工具,查询效率高,增删效率也高,还线程安全。因为数据结构的特性就是优劣共存,想找到平衡点很难。

不要为了用而用,要考虑性能性能,安全性之类的。

数组的大小是定长的,如果我们不断的往里面添加数据的话,不会有问题吗?

ArrayList通过构造方法在初始化的时候指定了底层数组的大小。

/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
 * 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);
    }
}

通过无参构造的方式 ArrayList() 初始化,则复制底层数组 Object[] elementDate为一个默认的空数组Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {} 所以数组的容量为0,只有真正对数据进行添加时,才分配默认 DEFAULT_CAPACITY = 10的初始容量。

数组的长度是有限制的,而ArrayList是可以存放任意数量对象,长度不受限制,那么他是怎么实现的呢?

方式比较简单,是通过数组扩容的方式去实现的。

比如我们有一个长度为10的数组,现在我们奥新增一个元素,发现已经满了,ArrayList会怎么做?

img

第一步他会重新定义一个长度为10+10/2的数组,也就是新增一个长度为15的数组。

img

然后他把元数组的数据原封不动的复制到新的数组中,这个时候再把指向元数的地址换到新数组,ArrayList就这样完成了改头换面。

img

ArrayList的默认大小是多少?

/**
 * 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

默认是空数组,只有第一次add的时容量会变成10。

ArrayList在增删的时候是怎么做的么?主要说一下他为啥慢。

他有指定index新增,也有直接新增的,在这之前他会有一步校验长度的判断ensureCapacityInternal,就是说如果长度不够,是需要扩容的。

/**
 * Appends the specified element to the end of this list.
 *
 * @param e element to be appended to this list
 * @return {@code true} (as specified by {@link Collection#add})
 */
public boolean add(E e) {
    modCount++;
    add(e, elementData, size);
    return true;
}
/**
 * Inserts the specified element at the specified position in this
 * list. Shifts the element currently at that position (if any) and
 * any subsequent elements to the right (adds one to their indices).
 *
 * @param index index at which the specified element is to be inserted
 * @param element element to be inserted
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public void add(int index, E element) {
    rangeCheckForAdd(index);
    modCount++;
    final int s;
    Object[] elementData;
    if ((s = size) == (elementData = this.elementData).length)
        elementData = grow();
    System.arraycopy(elementData, index,
                     elementData, index + 1,
                     s - index);
    elementData[index] = element;
    size = s + 1;
}

比如有下面这样一个数组我需要在index 5的位置去新增一个元素A

img

那从代码里面我们可以看到,他复制了一个数组,是从index 5的位置开始的,然后把它放在了index 5+1的位置

img

给我们要新增的元素腾出了位置,然后在index的位置放入元素A就完成了新增的操作了

img

至于为啥说他效率低,我想我不说你也应该知道了,我这只是在一个这么小的List里面操作,要是我去一个几百几千几万大小的List新增一个元素,那就需要后面所有的元素都复制,然后如果再涉及到扩容啥的就更慢了不是嘛。

ArrayList是线程安全的吗?

不是,线程安全的数组容器是vector。

Vector的实现很简单,就是把所有方法加上了synchronize。

ArraList适合做队列吗?

队列一般是FIFO(先入先出),如果用ArrayList做队列,就需要在数组尾部追加数据,数组头部删除数据。

凡是无论如何总会有一个操作涉及到数据的数据迁移,这个是比较耗费性能的。

所以ArrayList不适合做队列。

总结

ArrayList就是动态数组,他提供了动态的增加和减少元素,实现了Collection和List接口,灵活的设置数组大小等好处。

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

ArrayList常见用法总结

// 将指定的元素添加到此列表的尾部。
public boolean add(E e) {}
// 将指定的元素插入此列表中的指定位置。
public void add(int index, E element) {}
// 按照指定 collection 的迭代器所返回的元素顺序,将该 collection 中的所有元素添加到此列表的尾部。
public boolean addAll(Collection<? extends E> c) {}
// 从指定的位置开始,将指定 collection 中的所有元素插入到此列表中。
public boolean addAll(int index, Collection<? extends E> c) {}
// 移除此列表中的所有元素。
public void clear() {}
// 返回此 ArrayList 实例的浅表副本。
public Object clone() {}
// 如果此列表中包含指定的元素,则返回 true。
public boolean contains(Object o) {}
// 按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组。
public Object[] toArray() {}
// 按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。
public <T> T[] toArray(T[] a) {
posted @ 2020-04-02 13:43  没有故事的安徒生  阅读(211)  评论(0编辑  收藏  举报