大家都知道ArrayList底层就是一个可变的数组,所以我在这里使用课表数组简易的写一个MyArrayList
package com.zzq.me;
public class MyArrayList<T> {
private Object [] value;
private int size;
public MyArrayList () {
this(10);
}
public MyArrayList (int capacity) {
value = new Object[capacity];
}
@SuppressWarnings("unchecked")
public T get(int index) {
checkRang(index);
return (T)value[index];
}
public MyArrayList<T> add(T t){
enTrueCapacity();
value[size++]=t;
return this;
}
public int size() {
return this.size;
}
void checkRang(int index){
if(index<0 || index > value.length-1){
throw new IndexOutOfBoundsException();
}
}
void enTrueCapacity() {
if(size>this.value.length-1) {
Object [] newArr = new Object[this.value.length*2+2];
System.arraycopy(value, 0, newArr, 0, value.length);
value = newArr;
}
}
}