其他
ArrayList 的使用及原理,面试必问的知识点
点击上方 Java后端,选择 设为星标
优质文章,及时送达
为后面的面试做准备,今天复习一下 ArrayList ,这是必问的知识点
在开始之前给大家说一下,昨天发布了《今天面试了吗》系列文章第一篇,看来大家分享喜欢此系列,会继续更新。大家可以标星(置顶)本公众号:Java后端,获取后续更新。
ArrayList属于Collection集合类大家族的一员,是分支List中的主力军之一。ArrayList使用非常广泛,无论是在数据库表中查询,还是网络信息爬取都需要使用,所以了解ArrayList的原理就十分重要了(本文中若无特地说明,ArrayList版本基于JDK 1.8)。
ArrayList的继承关系
如何定义一个ArrayList?
ArrayList有三个构造函数:① 无参;②参数为整数;③参数为集合。
举个栗子:
//默认创建一个ArrayList集合
ArrayList<String> a1 = new ArrayList<>();
//创建一个初始长度为12的ArrayList集合
ArrayList<String> a2 = new ArrayList<>(12);
//将其他类型的集合转为ArrayList
ArrayList<String> a3 = new ArrayList<>(new HashSet());
/**
* 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;
ArrayList有参构造函数——入参类型为整型
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);
}
}
可以看到,如果传入正整数,则elementData数组容量初始化为initialCapacity;如果传入0,则elementData数组赋值为一个空数组。可能有读者发现了ArrayList类中有两个属性定义为空数组。
为什么ArrayList会定义两个空数组?
/**
* 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.
此共享空数组用于默认大小的空实例。我们将此与EMPTY_ELEMENTDATA区分开,以了解填充第一个元素时需要多少(空间)
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
ArrayList有参构造函数——入参类型为集合类
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
this.elementData = EMPTY_ELEMENTDATA;
}
}
可以看到,只要是实现了Collection的集合类,都会调用toArray()将集合类中的数组赋给elementData。而且toArray()返回的数组类型不是Object[]类型时…等等,toArray()返回的数组类型为什么会不是Object[]类型?举个栗子:
public class Test<E> extends ArrayList {
@Override
public Integer[] toArray() {
return new Integer[]{0, 23};
}
public static void main(String[] args){
Object[] elementData = new Test<Integer>().toArray();
System.out.println(elementData.getClass());
System.out.println(Object[].class);
System.out.println(elementData.getClass() == Object[].class);
}
}
class [Ljava.lang.Integer;
class [Ljava.lang.Object;
false
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
ArrayList无参构造函数
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
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);
}
}
public ArrayList() {
this(10);
}
怎么使用ArrayList?
ArrayList<String> list = new ArrayList<>();
list.add("双皮奶");
list.add("云吞面");
list.add("煲仔饭");
list.add("叉烧包");
list.add("艇仔粥");
list.add("糯米鸡");
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
protected transient int modCount = 0;
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)
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
set(int index, E element)
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
remove(int index)和remove(Object o)
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;
}
其他方法
size():用于获取集合的长度,可通过定义在ArrayList中的私有变量size得到。 isEmpty():用于确定ArrayList是否为空,可通过定义在ArrayList中的私有变量size得到。 contains(Object o):用于确定ArrayList是否包含某个元素,先通过遍历底层数组elementData,再通过equals或==判断。 clear():将ArrayList里的数据清空,通过遍历底层数组elementData,将数组里的值都设置为null。
结语