ArrayList概述
ArrayList是Java集合框架中一个经典的实现类。它比起常用的数组而言,明显的优点在于,可以随意的添加和删除元素而不需考虑数组的大小。
出于练手的目的,实现一个简单的ArrayList,并且把过程记下来。
基本API
默认构造器和一个参数的有参构造器
1. add方法
2. get方法
3. indexOf方法
4. contains方法
5. size方法
6. isEmpty方法
7. remove方法
实现
CustomArrayList.java
public CustomArrayList(){
this(DEFAULT_CAPACITY);
}
public CustomArrayList(int size){
if (size < 0){
throw new IllegalArgumentException("size参数非法:" + size);
}else{
elementData = new Object[size];
}
}
add
public void add(E e){
isCapacityEnough(size + 1);
elementData[size++] = e;
}
private void isCapacityEnough(int size){
if (size > DEFAULT_CAPACITY){
explicitCapacity(size);
}
if (size < 0){
throw new OutOfMemoryError();
}
}
判断扩容
判断扩容的方法也很简单,判断需要扩容的空间是不是比默认的空间大。
private final static int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8;
private void explicitCapacity(int capacity){
int newLength = elementData.length * 2;
if (newLength - capacity < 0){
newLength = capacity;
}
if (newLength > (MAX_ARRAY_LENGTH)){
newLength = (capacity > MAX_ARRAY_LENGTH ? Integer.MAX_VALUE : MAX_ARRAY_LENGTH);
}
elementData = Arrays.copyOf(elementData, newLength);
}
get方法
get方法用来得到容器中指定下标的元素。
private void checkRange(int index) {
if (index >= size || index < 0){
throw new IndexOutOfBoundsException("指定的index超过界限");
}
}
public E get(int index){
checkRange(index);
return (E)elementData[index];
}
indexOf
indexOf方法用来得到指定元素的下标
public int indexOf(Object o){
if (o != null) {
for (int i = 0 ; i < size ; i++){
if (elementData[i].equals(o)){
return i;
}
}
}else {
for (int i = 0 ; i < size ; i++){
if (elementData[i] == null) {
return i;
}
}
}
return -1;
}
contains方法
contains用来判断该容器中是否包含指定的元素
public boolean contains(Object o){
return indexOf(o) >= 0;
}
size方法
size方法用来得到容器类的元素个数,实现很简单,直接返回size的大小即可。
public int size(){
return size;
}
isEmpty方法
public boolean isEmpty(){
return size() == 0;
}
remove方法
第一个remove方法是核心方法,首先得到要删除的下标元素的值,然后判断index后面的要前移的元素的个数,如果个数大于零,则调用库方法,将index后面的元素向前移一位。最后elementData[–size] = null;缩减size大小,并将原最后一位置空。
public E remove(int index) {
E value = get(index);
int moveSize = size - index - 1;
if (moveSize > 0){
System.arraycopy(elementData,index + 1, elementData,index,size - index - 1);
}
elementData[--size] = null;
return value;
}
public boolean remove(Object o){
if (contains(o)){
remove(indexOf(o));
return true;
}else {
return false;
}
}
(完)