java当中的集合,使用最多莫过于ArrayList。上节课我们说过,ArrayList是一个数组型 的有序列表。
那么我们今天就来一一了解下它的创建,使用 和 实现。
今天的内容:
1、ArrayList
2、ArrayList的使用
3、ArrayList是如何实现的?
4、总结
第一部分:ArrayList
ArrayList是数组型的有序列表集合。位于java.util包下。定义为:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
ArrayList是List接口的实现。我们提到ArrayList是个有序列表,任何添加到其中的元素,默认是追加到列表的后面。
ArrayList 继承了AbstractList,实现了List。它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能。
ArrayList 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。
在ArrayList中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。
ArrayList 实现了Cloneable接口,即覆盖了函数clone(),能被克隆。
ArrayList 实现java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。
ArrayList还提供了一些元素的增删改查的方法。
第二部分:ArrayList的使用
ArrayList使用:
1、创建ArrayList的对象
2、调用方法进行元素的增删改查
创建ArrayList对象:
方式一:ArrayList list = new ArrayList();
方式二:List list = new ArrayList();
方式三:
ArrayList<User> list = new ArrayList<User>();
List<User> list = new ArrayList<User>();(建议)
方式四(jdk1.7以上):List<User> list = new ArrayList<>();
方法:
添加元素:
list.add(Object obj); 添加元素到集合的尾部。 此处obj是对象类型,list.add(1)时,会自动装箱。
list.add(int index,Object obj); 添加元素到集合中的指定位置,index从0起算。
删除元素:
list.remove(int index); 删除指定位置的元素,index从0起算
list.remove(Object obj) 删除集合中指定的元素。集合中元素是否和指定元素相同依靠对象的equals方法,默认是==。如果需要自定义规则,请重写equals方法。
修改元素:
list.set(int index,Object obj); 替换指定位置的元素,index从0起算。
查询元素:
list.get(int index) 获取指定位置的元素,index从0起算
清空集合:
list.clear();
是否包含某个元素:
list.contains(Object obj)
获取某个元素的位置
list.indexOf(Object obj)
判断集合是否为空
list.isEmpty()
获取集合中的元素个数
list.size()
排序数组
list.sort(Comparator c); 为数组排序,参数为一个实现了comparator接口的类
将集合转为数组
list.toArray() 得到Object[] 数组
lsit.toArray(Object[] a) 得到与指定类型匹配的数组
获取遍历器
list.iterator()
集合的遍历:三种方式
1、for
for(int i =0;i<list.size();i++){
Object o = list.get(i);//获取当前元素
}
2、foreach
for(Object o:list){//此处Object代表集合的元素类型,如List<User>则为User
o.getName();//当前元素o
}
3、迭代器(iterator)
Iterator i = list.iterator();
while(i.hasNext()){
Object o = i.next();//当前遍历对象
i.remove();//移除当前元素
}
第三部分:ArrayList的实现
ArrayList底层是使用一个数组实现的,也就是说,ArrayList是一个方便使用的,以数组为基础的对象。
在使用ArrayList时,我们不再关心容量的问题,也不关心具体怎么操作数组,非常方便。
我们以jdk1.8的源码一一来分析:
private static final int DEFAULT_CAPACITY = 10;
指定ArrayList的默认容量大小,也就是存储值的数组的大小。
private static final Object[] EMPTY_ELEMENTDATA = {};
默认的集合为空时数组的值。
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
也是默认的空集合时值数组,为了区分当添加元素后,空数组扩容后与原来的大小的对比。
一般扩容为10,这时候就需要一个参照来对比,确认元素的增长量。
transient Object[] elementData;
存储元素的数组对象。集合的容量也就是这个对象的大小。集合的大小也就是数组当中元素的个数。
之所以没有声明为私有,是由于需要内部类访问。
声明为transient是由于ArrayList需要序列化,但是数组这时候可能有空元素对象,全部序列化的话会产生额外的对象。
这时候声明transient禁止将数组序列化,而定义writeToObject方法来自定义序列化行为,这样只会序列化不为空的元素到流当中。
一个空的集合默认元素为DEFAULTCAPACITY_EMPTY_ELEMENTDATA ,当添加一个元素后,扩容到DEFAULT_CAPACITY
private int size;
表示集合的大小(集合包含元素的多少)。
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);
}
}
集合的构造函数(带初始指定容量)。如果指定容量大于0,就构造一个指定容量的数组。
如果指定容量为0,就使用空容量。否则,抛出异常。
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
集合的构造函数,不带指定容量。这时,使用默认的空数组。
public ArrayList(Collection<? extends E> 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;
}
}
集合的构造函数,传入一个collection集合作为初始元素集合。如果集合不为空,则将集合的元素拷贝到ArrayList。
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
将集合的容量缩减到元素的个数大小。一般不建议使用。
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 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);
}
缩减集合的容量到指定的容量,但是以保证所有元素都可以存储下为宗旨。所以,指定比元素个数小的容量不生效。
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
集合允许的最大数组范围。
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;
}
增长集合的容量到指定的范围。也以保证元素个数为宗旨。容量小于元素个数不生效。
public int size() {
return size;
}
得到集合当中元素的个数。
public boolean isEmpty() {
return size == 0;
}
集合是否为空。元素个数是否为0。
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
集合是否包含某个元素。
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
返回指定元素在集合当中(从第一个元素到最后一个)位置。如果是null,返回集合中的第一个null位置。否则,返回第一个equals指定元素的位置。
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
返回指定元素在集合当中的位置(从最后一个到第一个元素)。如果是null,返回集合中的第一个null位置。否则,返回第一个equals指定元素的位置。
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
返回集合的拷贝
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
返回集合的元素数组。返回类型Object[]
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
返回集合的元素数组,以指定的对象类型。
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
获取指定位置元素,类内部使用方法。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
获取集合中指定位置的元素。获取前需要检查位置的范围是否合法。
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
将元素添加到集合中的指定位置。设置时需要检查位置是否合法。
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
添加元素到集合当中。默认添加到集合数组的最后一个元素后。需要判断是否扩容。
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
添加指定元素到集合的指定位置。添加时需要检查位置范围是否合法。需要判断是否扩容。
添加到指定位置时,如果指定位置存在元素,那么该位置及以后的元素往后顺移一位。
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;
}
移除指定位置的元素。移除时需要检查位置是否合法。移除后,该位置后的元素需要往前顺移一位。
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; // clear to let GC do its work
}
移除集合中指定的元素。如果元素为空,移除从前往后数的第一个null对象。如果不为空,移除第一个equals指定元素的对象。
移除后,需要顺移后续元素。
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
清空集合当中的元素。清空时,只是将各个位置的元素置为null,size置为0。内部数组并没有缩小。
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
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); // Increments modCount
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;
}
添加一个集合到当前集合当中的指定位置。指定位置及以后的元素顺延参数集合的元素个数。
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
移除集合当中的一段元素。从指定开始位置到指定结束范围的元素被删除。
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
范围检查及报错内容输出。
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) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
批量移除元素,集合类内部使用方法。
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// Write out all elements in the proper order.
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
集合输出到流的序列化方法。
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
从流读取对象到集合的方法。
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
返回集合当中指定位置之后的元素listiterator对象。
public ListIterator<E> listIterator() {
return new ListItr(0);
}
返回所有元素的listiterator对象
public Iterator<E> iterator() {
return new Itr();
}
返回集合的 iterator
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
集合的iterator实现
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
集合的listiterator实现。
其他的部分属于非核心部分,不做具体的说明。
第四部分:总结
存放可重复元素的集合,默认存放有顺序(最后)。
内部维护一个存储数组
使用本地方法操纵数组扩容(默认扩容0.5倍),复制等
维护长度,当前容量等内部属性,内部实现数组对元素的操纵,对外提供操纵方法入口
获取元素直接使用数组的arr[i],复杂度O(1).
增加删除修改指定位置的元素时,需要一一遍历数组,复杂度O(n)。默认在最后增加元素。
线程不安全