数据结构与算法分析-ArrayList的实现

/*
*ArrayList的实现类
*/

public class MyArrayList<AnyType> implements Iterable<AnyType> {  //Iterable表示该类支持迭代
	private static final int DEFAULT_CAPACITY=10;  //设定一个初始容量为10;
	private int theSize;        //该容器的大小
	private AnyType[] theItems; //用数组来实现该容器
	
	public void ensureCapacity(int newCapacity){ //初始化容器和扩展容器
		if(newCapacity<theSize){                  //查看要扩展的大小是否大于原来的大小
			return;
		}
		AnyType [] oldItems=theItems;             //把里面存在的数据存到OldItems里面
		theItems=(AnyType []) new Object[newCapacity]; //重新给theItems分配空间
		for(int i=0;i<size();i++){
			theItems[i]= oldItems[i];                  //把数据转移到theItems
		}
		
	}
	
	public int size(){        //容器的大小
		return theSize;
	}
	public MyArrayList(){    //构造方法
		doClear();
	}
	
	private void doClear(){
		theSize=0;
		ensureCapacity(DEFAULT_CAPACITY); //初始化容器大小
	}
	
	public void clear(){   //数据清除
		doClear();
	}
	
	public AnyType get(int index){  //通过下表获取数据
		if(index<0||index>=size()){   //index等于size()也不行是因为数组下标是从0开始的到size()-1;
			throw new ArrayIndexOutOfBoundsException();  //如果下标越界则抛出异常
		}
		return theItems[index];
	}
	
	public AnyType set(int index,AnyType newVal){  //给表中的数据设值,返回原数据
		if(index<0||index>=size()){
			throw new ArrayIndexOutOfBoundsException();
		}
		AnyType oldVal=theItems[index];   //先将以前的值存储起来,方便返回
		theItems[index]=newVal;           //给指定位置赋值
		return oldVal;                    //返回以前的值
	}
	
	public void trimToSize(){   //该方法可以减少内存占用,将原来多余的内存释放.
		ensureCapacity(size()); 
	}
	
	public boolean isEmpty(){   //判断是否为空
		return size()==0;
	}
	
	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);  //后面加1是因为size有时可能是0的情况
		}
		for(int i=size();i>index;i--){
			 theItems[i]=theItems[i-1];
		}
		theItems[index]=x;
		theSize++;
	}
	
	/*
	*
	*删除要把指定位置后的数据向前移
	*/
	public AnyType remove(int index){   //返回删除的数据
		AnyType removeItem=theItems[index];
		for(int i=index;i<size()-1;i++){
			theItems[i]=theItems[i+1];
		}
		theSize--;
		return removeItem;
	}
	public java.util.Iterator<AnyType> iterator(){
		return new ArrayListIterator();
	}
	
	private class ArrayListIterator implements java.util.Iterator<AnyType>{
		private int current = 0;  //代表当前的指针
		
		public boolean hasNext(){   //判断是否还有下一个数据
			return current<size();
		}
		
		public AnyType next(){  //返回下一个数据
			if(!hasNext()){
				throw new java.util.NoSuchElementException();
			}
			return theItems[current++];
			
		}
		public void remove(){
			MyArrayList.this.remove(--current);
		}
		
	}
	
} 

猜你喜欢

转载自blog.csdn.net/qq_30092289/article/details/86564653