实现简单arrayList

来源:互联网 发布:投诉淘宝店铺投诉电话 编辑:程序博客网 时间:2024/06/07 11:28
/**
 * 实现arrayList 
 * 53页
 * @author zj
 *
 * @param <T>
 */
public class MyArrayList<T> implements Iterable<T> {

private static final int DEFAULT_CAPACITY = 10;

/*
* 大小及数组作为数据成员进行存储
*/
private int theSize;
private T[] theItems;

public MyArrayList(){
clear();
}


private void clear() {
// TODO Auto-generated method stub
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}


/**
* 容量扩充
* @param newCapacity
*/
private void ensureCapacity(int newCapacity) {
// TODO Auto-generated method stub
if(newCapacity < theSize)return;

T[] old = theItems;
theItems = (T[]) new Object[newCapacity];
for(int i = 0;i<size();i++){
theItems[i] = old[i];
}
}




private int size() {
// TODO Auto-generated method stub
return theSize;
}

public void trimToSize(){
ensureCapacity(size());
}

public boolean isEmpty(){
return size() == 0;
}

public T  get(int idx){
if(idx < 0 || idx >= size())
throw new ArrayIndexOutOfBoundsException();
return theItems[idx];
}

public T set(int idx , T newVal){
if(idx < 0 || idx >=size())
throw new ArrayIndexOutOfBoundsException();
T old = theItems[idx];
theItems[idx] = newVal;
return old;
}


public  boolean add(T x){
add(size(),x);
return true;
}
private void add(int idx, T x) {
// TODO Auto-generated method stub
if(theItems.length == size())
ensureCapacity(size()*2+1);
for( int i = theSize;i>idx;i--){//如果不是末端add,在插入位置依次往后移位
theItems[i] = theItems[i-1];
}
theItems[idx] = x;
theSize++;
}


public T remove(int idx){
T removedItem = theItems[idx];
for(int i = idx;i<size()-1;i++){
theItems[i] = theItems[i+1];
}
theSize--;
return removedItem;
}


@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return  new ArrayListIterator();
}
private class ArrayListIterator implements java.util.Iterator<T>{


private int current = 0;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return current < size();
}


@Override
public T next() {
// TODO Auto-generated method stub
if(!hasNext())
throw new java.util.NoSuchElementException();
return theItems[current++];
}


@Override
public void remove() {
// TODO Auto-generated method stub
MyArrayList.this.remove(--current);
}

}
public static void main(String[] args) {
MyArrayList<Integer> ma = new MyArrayList<Integer>();
ma.add(1);
ma.add(2);
}
}
0 0