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)); } }
顺序表实现
猜你喜欢
转载自tracy-lcz.iteye.com/blog/1162143
今日推荐
周排行