public class MyArrayList<T> implements Iterable<T> {
private int capacity = 16;
private int size = 0;
private T array [];
@Override
public Iterator<T> iterator() {
return null;
}
public MyArrayList() {
super();
}
public MyArrayList(int capacity ) {
this.capacity = capacity;
}
public int size(){
return size;
}
public boolean isEmplty(){
return size ==0;
}
public T get(int index){
if (index < 0 || index>=size) {
throw new IndexOutOfBoundsException();
}
return array[index];
}
public void set(int index,T t){
if (index < 0 || index>=size) {
throw new IndexOutOfBoundsException();
}
array[index] = t;
}
public void ensureCapacity(){
if (array.length == size) {//当和数组长度相同时候 需要扩容了//扩容方案为原长度8*2
T [] newArray = (T[]) new Object[size*2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
}
public T add(T t){
ensureCapacity();
array[size] = t;
size++;
return t;
}
ArrayList简单实现
最新推荐文章于 2022-08-10 00:27:05 发布