表--MyArrayList的实现

来源:互联网 发布:什么是js脚本 编辑:程序博客网 时间:2024/06/05 07:43
package List;


import java.util.Iterator;
import java.util.NoSuchElementException;


/**
 * @author hadoop
 *MyArrayList将提供一个实现Iterator接口的类,这个类将存储迭代序列中的下一项的下标;
 *MyArrayList的迭代器方法直接返回实现Iterator接口的该类的新构造实例;
 */
public  class MyArrayList<AnyType> implements Iterable <AnyType>{

public static final int DEFAULT_CAPACITY = 10;//创建默认基础数组容量
public int theSize;
public AnyType [] theItems;

public MyArrayList(){
clear();
}
public void clear(){
theSize =0;
ensureCapacity(DEFAULT_CAPACITY);
}

public int size(){
return theSize;
}

public boolean isEmpty(){
return size() ==0;
}
//调整容量符合大小
public void trimToSize(){
ensureCapacity(size());
}


public AnyType get (int index){
if(index<0||index>=size()){
throw new ArrayIndexOutOfBoundsException();

}
return theItems[index];

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

}

public void ensureCapacity(int newCapacity){
if(newCapacity<theSize)
return;
AnyType[] old=theItems;//行存储对原始数组的一个引用
theItems=(AnyType[])new Object[newCapacity];//为新数组分配内存
for(int i =0;i<size();i++)//将旧内容拷贝到新数组中
theItems[i]=old[i];

}
public boolean add(AnyType x){
add(size(),x);
return true;

}

//顺序表添加一个数据
public void add(int index,AnyType x){
//数组不够大,为数组扩容
if(theItems.length==size())
ensureCapacity(size()*2+1);
//往后移动一位
for(int i=theSize;i>index;i--){
theItems[i]=theItems[i-1];
}
theItems[index]=x;
theSize++;
}

//顺序表删除一个数据
public AnyType remove(int index){
AnyType removeItems=theItems[index];
for(int i=index;i<size()-1;i++){
theItems[i]=theItems[i+1];

}
theSize--;
return removeItems;

}

//iterator方法和相关迭代器类的实现

public Iterator<AnyType> iterator() {
// TODO Auto-generated method stub
return new ArrayListIterator();
}
public class ArrayListIterator implements Iterator<AnyType>{
private int current =0;
public boolean hasNext(){
return current <size();
}

public AnyType next(){
if(!hasNext())
throw new NoSuchElementException();
return theItems[current++];
}
public void remove(){
MyArrayList.this.remove(--current);
}


}



}
0 0