あなたのシリーズを削り殺します——手はArrayListを引き裂きます
6699 ワード
多くないBB、直接コードをつけます:
public class MyArrayList {
//
private Object[] elements;
//
private int size = 0;
//
private final static int INIT_LENGTH = 10;
//
private int static int MAX_LENGTH = Integer.MAX_VALUE;
//
public MyArrayList() {
this(INIT_LENGTH);
}
//
public MyArrayList(int capacity) {
if (capacity < 0) {
System.out.println(" ");
}
elements = new Object[capacity];
}
//
public int size() {
return size;
}
//
public boolean isEmpty() {
return size == 0;
}
//
public void add(E e) {
checkCapacity(size);
elements[size++] = e;
}
//
public void add(int index, E e) {
checkRange(index);
checkCapacity(size);
System.arraycopy(elements, index, elements, index + 1, size - index);
elements[index] = e;
size++;
}
//
public E get(int index) {
checkRange(index);
return elements[index];
}
//
public E remove(int index) {
checkRange(index);
int moveSize = size - index - 1;
E value = get(index);
//
if (moveSize > 0) {
System.arraycopy(elements, index + 1, elements, index, moveSize);
}
elements[size--] = null;
return value;
}
//
public void checkRange(int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(" ");
}
}
//
public void checkCapacity(int size){
if(size == elements.length){
int newLength = size<<1 < MAX_LENGTH ? size<<1 : MAX_LENGTH;
elements = Arrays.copyOf(elements, newLength);
}
}
}