public class MyArrayList<E> {
private int size;
private Object[] objects;
private static final int INITIAL_SIZE = 16;
public MyArrayList() {
objects = new Object[INITIAL_SIZE];
}
public int size() {
return size;
}
public boolean add(E e) {
if (size == objects.length) {
transferArr();
}
objects[size] = e;
size++;
return true;
}
public boolean add(int index, E e) {
if (index >= size) {
throw new ArrayIndexOutOfBoundsException();
}
if (size == objects.length) {
transferArr();
}
System.arraycopy(objects, index, objects, index + 1, size - index);
objects[index] = e;
size++;
return true;
}
private void transferArr() {
int length = objects.length;
int half = length >> 1;
length = length + half;
Object[] newArr = new Object[length];
System.arraycopy(objects, 0, newArr, 0, objects.length);
objects = newArr;
}
public E get(int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException();
}
return (E) objects[index];
}
public E remove(int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException();
}
Object object = objects[index];
if (index == (size - 1)) {
objects[index] = null;
} else {
System.arraycopy(objects, index + 1, objects, index, size - index);
}
size--;
return (E) object;
}
public E set(int index, E e){
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException();
}
Object oldVal = objects[index];
objects[index] = e;
return (E) oldVal;
}
public int arrLength() {
return objects.length;
}
}