接口和实现类分析:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
- 继承了AbstractList,实现了List 它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能
- 实现了RandmoAccess接口 即提供了随机访问功能
- 实现了Cloneable接口 即覆盖了函数clone(),能被克隆
- 实现java.io.Serializable接口 支持序列化,能通过序列化去传输
深入理解:
1.RandmoAccess
打开之后发现这是一个空类,通过官网查阅可知。这只是一个标志性接口,没有方法。
官方描述:
public interface RandomAccess
Marker interface used by List implementations to indicate that they support fast (generally constant time) random access.
…
a List implementation should implement this interface if, for typical
instances of the class, this loop:for (int i=0, n=list.size(); i < n; i++) list.get(i); runs faster than this loop: for (Iterator i=list.iterator(); i.hasNext(); ) i.next();
意思就是:实现这个这个接口的 List 集合是支持快速随机访问的。也就是说,实现了这个接口的集合是支持 快速随机访问 策略的。
同时,官网还特意说明了,如果是实现了这个接口的 List,那么使用for循环的方式获取数据会优于用迭代器获取数据
2.Cloneable接口
该接口仅是一个标记,没有方法
Cloneable是标记型的接口,它们内部都没有方法和属性,实现
Cloneable来表示该对象能被克隆,能使用Object.clone()方法。如果没有实现
Cloneable的类对象调用clone()就会抛出CloneNotSupportedException。
3.Serializable接口
该接口仅是一个标记,没有方法
- Serializable接口:实现该**序列化接口,表明该类可以被序列化。**什么是序列化?简单的说,就是能够从类变成字节流传输,然后还能从字节流变成原来的类。
4.继承了AbstractList
ArrayList和AbstractList都实现了List接口的方法。。。
但为什么ArrayList不直接使用父类的呢?这是一个差不多历史遗留问题
源码解析和阅读
ArrayList是一个不定长数组。容量是动态增长的。
下面来认识一下该类中的重要属性
.1. 默认容量
private static final int DEFAULT_CAPACITY = 10;
2.元素数量
private int size;
- 空的对象数组
//空的数组,容量为0.。。
private static final Object[] EMPTY_ELEMENTDATA = {};
4.默认的空数组
// 无参构造函数创建的数组,容量为10
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
5.存放数据的数组的缓存变量,不可序列化
transient Object[] elementData;
1.构造函数
提供了三个构造函数
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
//不规定长度,此时默认为10
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
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);
}
}
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;
}
}
2.添加元素的方法
有两种添加元素的方法
public boolean add(E e) {
//确保数组容量足够,并及时动态扩展
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public void add(int index, E element) {
//越界检查,查看index在不在范围
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
System.arraycopy(elementData, index, elementData, index + 1,
size - index);//该方法是讲数组index向后移动一位,
意思是,把elementData从index开始的内容copy到elementData从>index+1的地方,且长度为size-index
ensureCapacityInternal方法
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);
}
grow方法
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//扩展为1.5倍
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;
}
Arrays.copyOf()方法,底层调用仍然是System.arraycopy
动态扩容,传入的第二个参数就是扩容的大小。。扩容后原来数据不受影响
3.删除元素的方法
与增加元素的方法一样同样是两个方法
public E remove(int index) {
rangeCheck(index);//检查IndexOutOfBoundsException
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
}
4.迭代器
这里有一个内部类
需要注意的是,使用迭代器或者增强for去遍历的时候,是不能直接调用remove方法的。。否则会抛出异常
代码是怎么实现的呢
int expectedModCount = modCount;//在这里使用一个变量expectedModCount,其值与modCount相等
/**
每次非迭代器类的删除操作都会把modCount改变
*/
modCount++;
//迭代器的每轮变量都会判断,不相等就抛出异常....
checkForComodification();
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
//所以我们在使用迭代器或增强for遍历的时候
//该如何删除呢?举个栗子
List<Integer> list =new ArrayList<>();
Iterator<Integer> it=list.iterator();
while(it.hasNext()){
Integer num=it.next();
if(){
it.remove();
}
}
//迭代器类里面的删除方法是ok的,他可以随时更改expectedModCount的值,具体强参照源码
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();
}
}
下面贴出迭代器的源码。。Itr是实现了Iterator接口,同时重写了里面的hasNext(),next(),remove()等方法;
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;
Itr() {}
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();
}
}
总结
ArrayList值地强调的是,他的删除和插入操作效率都是比较低的,但是他的变长特性又无比优越。。
与LinkedList形成鲜明对比。。。
以后再详细比较吧
给出一张图总结所学。
第一天开始学习源码。。挺枯燥的,内容也不齐全,有了再加吧