# ArrayList 底层是一个容量能够动态增长的数组
特点是: 可以随机的访问元素,但是增删改缓慢,他不是线程安全的,在单线程中是使用(多线程使用Vector或者CopyOnWriteArrayList)
1. 源码分析
1.构造方法:
ArrayList() // 构造一个初始容量为 10 的空列表。
ArrayList(int initialCapacity) // 构造一个具有指定初始容量的空列表。
ArrayList(Collection<? extends E> c) // 构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
2.方法摘要:
// Collection中定义的API
boolean add(E object)
boolean addAll(Collection<? extends E> collection)
void clear()
boolean contains(Object object)
boolean containsAll(Collection<?> collection)
boolean equals(Object object)
int hashCode()
boolean isEmpty()
Iterator<E> iterator()
boolean remove(Object object)
boolean removeAll(Collection<?> collection)
boolean retainAll(Collection<?> collection)
int size()
<T> T[] toArray(T[] array)
Object[] toArray()
// AbstractCollection中定义的API
void add(int location, E object)
boolean addAll(int location, Collection<? extends E> collection)
E get(int location)
int indexOf(Object object)
int lastIndexOf(Object object)
ListIterator<E> listIterator(int location)
ListIterator<E> listIterator()
E remove(int location)
E set(int location, E object)
List<E> subList(int start, int end)
// ArrayList新增的API
Object clone()
void ensureCapacity(int minimumCapacity)
void trimToSize()
void removeRange(int fromIndex, int toIndex)
2.理解
ArrayList实际上是通过一个数组去进行保存的,当创建ArrayList的时候会提供三个构造方法,
如果没有制定初始化数组的大小,默认为10
扩容是通过Arrays.copyof实现的 扩容的大小为1.5倍。
3. 使用数组实现ArrayList
package com.ld.arrayList;
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayToArrayList {
private Object[] data = null;
private int size = 0;
private static final int DEFAULT_CAPYCITY = 10;
public ArrayToArrayList (int length) {
if(length<0) {
throw new IllegalArgumentException("非法的数组容量");
}else {
this.data = new Object[length];
}
}
public ArrayToArrayList() {
this.data = new Object[DEFAULT_CAPYCITY];
}
public int length () {
return this.data.length;
}
public void grow() {
int newLength = this.data.length+(this.data.length<<1);
this.data = Arrays.copyOf(this.data, newLength);
}
public void add (Object obj) {
if(size >= this.data.length) {
this.grow();
}
this.data[size] = obj;
size++;
}
public void add(int index, Object obj) {
if(index<0 || index>this.data.length) {
throw new IllegalArgumentException("Index:"+index);
}
if(size >= this.data.length) {
this.grow();
}
System.arraycopy(data, index, data, index+1, size-index);
data[index] = obj;
size++;
}
public void remove(int index) {
if(index<0 || index>=data.length) {
throw new IllegalArgumentException("下标异常");
}
System.arraycopy(data , index+1, data, index, size-(index+1));
size--;
}
public void remove(Object obj) {
int index = indexOf(obj);
if(index!=-1) {
remove(index);
}
}
public int indexOf(Object obj) {
for(int i=0;i<data.length;i++) {
if(data[i]==obj || data[i]!=null && data[i].equals(obj)) {
return i;
}
}
return -1;
}
public void clear() {
size = 0;
}
public boolean contains (Object obj) {
int index = indexOf(obj);
if(index!=-1) {
return true;
}
return false;
}
}