public interface ListMethod {int size(); //判斷線性表是否為空白 boolean isEmpty(); //插入元素 void insert(int i, Object obj) throws Exception; //刪除元素 void delete(int i) throws Exception; //擷取指定位置的元素 Object get(int i) throws Exception;}
public class List implements ListMethod{//預設最大的長度為10;public static final int DefoultSIZE=10;//線性表最大長度int maxSize;//線性表list的當前度int length;//對象數組Object[] listArray;//對象數組public List( int length) {maxSize=length;this.length=0;listArray=new Object[length];}//判斷線性表是否為空白public boolean isEmpty() {if(length==0){return true;}return false;}@Overridepublic int size(){return length;}@Overridepublic void delete(int i) throws Exception {//刪除線性表第i各位置的元素if(isEmpty()){throw new Exception("該表空,無法刪除");}if(i<0||i>length-1){throw new Exception("該表刪除的位置越界,無法刪除");}for(int k=i;k<=length-1;k++){listArray[k-1]=listArray[k];}length--;}public Object get(int i) throws Exception {if(i<0||i>length-1){throw new Exception("參數有錯誤");}return listArray[i];}@Overridepublic void insert(int i, Object obj) throws Exception {if(length==maxSize){throw new Exception("位置已滿,別插了");}//如果你插入的位置比0小,或者你插入的位置比現在最大長度還大if(i<0||i>maxSize-1){throw new Exception("參數有錯誤");}for(int k=length-1;k>=i;k--){listArray[k+1]=listArray[k];}listArray[i] = obj;length++;}}