查看數組大小:
成功擴容為20大小的數組。
實現獲取pos位置元素和順序表的長度,以及設置元素這三個接口。由于獲取和設置元素都需要檢查下標是否合法。所以我們寫一個判斷位置是否合法的方法。我們在判斷非法的時候我們直接輸出非法不合適,我們應該建立一個異常,然后拋出異常.
建立異常:
public class PosOutBoundsException extends RuntimeException{
? ? public PosOutBoundsException() {
? ? }
? ? public PosOutBoundsException(String message) {
? ? ? ? super(message);
? ? }
}
接口的實現:
// 獲取 pos 位置的元素
public int get(int pos) ?{
? ? if (!checkPos(pos)){
? ? ? ? throw new RuntimeException("get 元素位置錯誤");
? ? }
? ? return this.elem[pos];
}
// 獲取順序表長度
public int size() {
? ? return this.usedSize;
}
// 給 pos 位置的元素設為 value【更新的意思 】
public void set(int pos, int value) {
? ? if (!checkPos(pos)){
? ? ? ? throw new RuntimeException("set 元素位置錯誤");
? ? }
? ? this.elem[pos] = value;
}
//檢查pos下表是否 合法
private boolean checkPos(int pos){
? ? if (pos < 0 || pos >= this.usedSize) return false;
? ? return true;
}
進行新增數據的測試 :
public static void main(String[] args) {
? ? SeqList seqList = new SeqList();
? ? seqList.add(1);
? ? seqList.add(2);
? ? seqList.add(3);
? ? seqList.add(4);
? ? seqList.add(5);
? ? seqList.add(6);
? ? System.out.println(seqList.get(3));
? ? seqList.display();
? ? seqList.set(3,1000);
? ? seqList.display();
? ? seqList.get(10);//獲取元素位置錯誤拋出異常。
}
最后輸出結果:
? ? 4
? ? 1 2 3 4 5 6
? ? 1 2 3 1000 5 6
? ? Exception in thread “main” java.lang.RuntimeException: get 元素位置錯誤
? ? at demoList2.SeqList.get(SeqList.java:56)
? ? at demoList2.Test.main(Test.java:17)