ArrayList api

Belle ·
更新时间:2024-11-15
· 568 次阅读

ArrayList api 一、概述

arrayList底层是通过数组实现,非线程安全的。

1、list初始化

其中 初始化因子 初始容量为10,HashMap为16

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

这里的elementData就是底层的数据。

2、list初始化时,构造方法可以传递list /** * 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 c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } } 3、add方法 /** * 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 = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } 4、remove方法 4.1按照索引进行删除

这里体现了数组的快捷

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; // clear to let GC do its work return oldValue; } 4.2按照元素进行删除(删除的为第一个元素)

从代码可以看出,元素删除是逐个遍历,然后删除第一个元素

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 remove method that skips bounds checking and does not * return the value removed. */ 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; // clear to let GC do its work } 二、总结 1、get方法

get目前只是按照index,可以加入按照元素来查找,我想应该有这样的需求吧

2、remove方法

为什么只提供删除第一个,可以全部删除吗?
实际上提供了

removeIf(Predicate.isEqual(2))

我觉得这个挺好的啊。

3、通过for循环进行删除

通过remove的代码分析,i++的方式是不可行的,i–的方式是可行的。但是最好用迭代器操作。


作者:zcoderz



arraylist api

需要 登录 后方可回复, 如果你还没有账号请 注册新账号