シーケンステーブル実装

2846 ワード


public class MyArrayList<E> {
	
	
	
	Object [] data=null; //   
	
	int current;    //  
	int capacity;   //  
	
	public MyArrayList(){
		this(10);
		}
    
	
	public MyArrayList(int initalSize){
		if(initalSize<0){
			throw new RuntimeException(" "+initalSize);
		}else{
			this.data=new Object[initalSize];
			this.current=0;
			this.capacity=initalSize;
			
		}
	}
	
	
	public boolean add(E e){
		ensureCapacity(this.current);
		this.data[this.current]=e;
		this.current++;
		return true;
	}
	
	
	private void ensureCapacity(int cur){
		if(cur==this.capacity){
			this.capacity=this.capacity+10;
			System.out.println(" !");
			Object[] newdata=new Object[this.capacity];
			for(int i = 0 ; i<cur;i++){
				newdata[i]=this.data[i];
			}
			this.data=newdata;
		}
	}
	
	@SuppressWarnings("unchecked")
	public E get(int index){
		validateIndex(index);
		
		return (E)this.data[index];
		
	}
	
	
	private void validateIndex(int index){
		if(index<0 || index>this.current){
			throw new RuntimeException(" index "+index);
		}
	}
	
	
	public boolean insert(int index,E e){
		
		 validateIndex(index);
		 
		 Object [] tem=new Object[this.capacity];
		 
         for(int i=0;i<this.current;i++){
        	 if(i<index){
        		 tem[i]=this.data[i];
        	 }else if(i==index){
        		 tem[i]=e;
        	 }else if(i>index){
        		 tem[i]=this.data[i-1];
        	 }
         }		 
         this.data=tem;
         
         return true;
	}
	
	
	
	public boolean delete(int index){
		validateIndex(index);
		
		Object[] tem=new Object[this.capacity];
		
		for(int i = 0 ; i<this.current;i++){
			if(i<index){
				tem[i]=this.data[i];
			}else if(i==index){
				
				tem[i]=this.data[i+1];
			}else{
				tem[i]=this.data[i+1];
			}
		}
		
		this.data=tem;
		
		return true;
		
	}
	
	/**
	 * @param args
	 * 
	 * author:jack_lcz
	 * 
	 * date: 2011-08-30
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		
		MyArrayList  ml=new MyArrayList();
		
		ml.add(" ");
		ml.add(" ");
		ml.delete(0);
		System.out.print(ml.get(0));
		
		

	}

}