List
public interface List<E> {
int ELEMENT_NOT_FOUND = -1;
void clear();
int size();
boolean isEmpty();
boolean contains(E element);
void add(E element);
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
int indexOf(E element);
}
AbstractList
package com.cj;
public abstract class AbstractList<E> implements List<E>{
protected int size;
@Override
public void add(E element) {
add(size, element);
}
@Override
public int size() {
return this.size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public boolean contains(E element) {
return indexOf(element) != ELEMENT_NOT_FOUND;
}
protected void outOfBounds(int index, int size) {
throw new IndexOutOfBoundsException("index:" + index + ",size:" + size);
}
protected void rangeCheckForAdd(int index) {
if (index < 0 || index > size) {
outOfBounds(index, size);
}
}
protected void rangeCheck(int index) {
if (index < 0 || index >= size) {
outOfBounds(index, size);
}
}
}
ArrayList
package com.cj;
public class ArrayList<E> extends AbstractList<E>{
public static final int DEFAULT_CAPACITY = 10;
private E[] elements;
public ArrayList(int capacity) {
capacity = (capacity < DEFAULT_CAPACITY) ? DEFAULT_CAPACITY : capacity;
elements = (E[]) new Object[capacity];
}
public ArrayList() {
this(DEFAULT_CAPACITY);
}
public E get(int index) {
rangeCheck(index);
return elements[index];
}
public E set(int index, E element) {
rangeCheck(index);
E old = elements[index];
elements[index] = element;
return old;
}
public int indexOf(E element) {
if (element == null) {
for (int i = 0; i < size; i++) {
if (elements[i] == null) return i;
}
} else {
for (int i = 0; i < size; i++) {
if (element.equals(elements[i])) return i;
}
}
return ELEMENT_NOT_FOUND;
}
public void clear() {
for (int i = 0; i < size; i++) {
elements[i] = null;
}
this.size = 0;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("size=").append(size).append(",[");
for (int i = 0; i < size; i++) {
if (i != 0) {
builder.append(",");
}
builder.append(elements[i]);
}
builder.append("]");
return builder.toString();
}
public E remove(int index) {
rangeCheck(index);
E old = elements[index];
for (int i = index + 1; i < size; i++) {
elements[i - 1] = elements[i];
}
elements[--size] = null;
return old;
}
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacity(size + 1);
for (int i = size - 1; i >= index; i--) {
elements[i + 1] = elements[i];
}
elements[index] = element;
size++;
}
private void ensureCapacity(int capacity) {
int oldCapacity = elements.length;
if (oldCapacity >= capacity) return;
int newCapacity = oldCapacity + (oldCapacity >> 1);
E[] newElements = (E[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
newElements[i] = elements[i];
}
elements = newElements;
System.out.println(oldCapacity + "扩容为:" + newCapacity);
}
}