import java.util.Arrays;
/**
* 自定义ArrayList
*/
public class MyArrayList {
private Object[] elementData = {};
private int size;
/**
* 构造方法
*/
public MyArrayList() { }
/**
* 数组大小
* @return
*/
public int size() {
return size;
}
/**
* 数组是否为空
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 扩容
* @param minCapacity
*/
private void grow(int minCapacity) {
if(minCapacity - elementData.length > 0) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if(newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
/**
* 检测下标是否越界
* @param index
*/
private void checkRange(int index) {
if(index >= size || index < 0) {
throw new IndexOutOfBoundsException();
}
}
/**
* 添加元素到末尾
* @param o
* @return
*/
public boolean add(Object o) {
grow(size + 1);
elementData[size++] = o;
return true;
}
/**
* 添加元素到指定位置
* @param index
* @param o
*/
public void add(int index, Object o) {
if(!(index <= size && index >= 0)) {
throw new IndexOutOfBoundsException();
}
grow(size + 1);
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = o;
size++;
}
/**
* 根据下标获取元素
* @param index
* @return
*/
public Object get(int index) {
checkRange(index);
return elementData[index];
}
/**
* 删除元素
* @param index
*/
private void fastRemove(int index) {
int numMoved = size - index - 1;
if(numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
}
/**
* 根据下标删除元素
* @param index
* @return
*/
public Object remove(int index) {
checkRange(index);
Object oldValue = get(index);
fastRemove(index);
return oldValue;
}
/**
* 根据元素删除数组中的元素
* @param o
* @return
*/
public boolean remove(Object o) {
if(o == null) {
for(int i = 0; i < size; i++) {
if(elementData[i] == null) {
fastRemove(i);
return true;
}
}
}else {
for(int i = 0; i < size; i++) {
if(o.equals(elementData[i])) {
fastRemove(i);
return true;
}
}
}
return false;
}
}