标签:
publicclassSeqList{ final int defaultSize =10; //默认的顺序表的最大长度 int maxSize; //最大长度 int size; //当前长度 Object[] listArray; //对象数组 publicSeqList(){ init(defaultSize); } publicSeqList(int size){ init(size); } //顺序表的初始化方法 privatevoid init(int size){ maxSize = size; this.size =0; listArray =newObject[size]; } publicvoiddelete(int index) throws Exception { //容错性 if(isEmpty()){ thrownewException("顺序表为空,无法删除!"); } if(index <0|| index > size -1){ thrownewException("参数错误!"); } //移动元素(从前往后操作) for(int j = index; j < size -1; j++) listArray[j]= listArray[j +1]; listArray[size -1]= null; //注意释放内存(避免内存泄漏) size--; } publicObject get(int index) throws Exception { if(index <0|| index >= size){ thrownewException("参数错误!"); } return listArray[index]; } publicvoid insert(int index,Object obj) throws Exception { //容错性 if(size == maxSize){ thrownewException("顺序表已满,无法插入!"); } if(index <0|| index > size){ thrownewException("参数错误!"); } //移动元素(从后往前操作) for(int j = size -1; j >= index; j--) listArray[j +1]= listArray[j]; listArray[index]= obj; size++; } public boolean isEmpty(){ return size ==0; } publicint size(){ return size; }}publicclassTest{ publicstaticvoid main(String[] args){ SequenceListlist=newSequenceList(20); try{ list.insert(0,100); list.insert(0,50); list.insert(1,20); for(int i =0; i <list.size; i++){ System.out.println("第"+ i +"个数为"+list.get(i)); } }catch(Exception e){ e.printStackTrace(); } }}
标签:
原文地址:http://www.cnblogs.com/Doing-what-I-love/p/5533088.html