資料結構-順序表(java)萌新寫的希望各位大佬提提意見
阿新 • • 發佈:2018-11-06
package bh.shy.list;
import bh.shy.listconst.ListConst;
public class MyList {
// 定義一個數組T private T[] t; private int length; private int listSize; // 獲取順序表的長度 public int getLength() { return this.length; } // 獲取順序表的容量 public int getListSize() { return this.listSize; } // 建構函式初始化一個包含100個元素的順序表 @SuppressWarnings("unchecked") public MyList() { t = (T[]) new Object[ListConst.INIT_LIST_SIZE]; this.length = 0; this.listSize = ListConst.INIT_LIST_SIZE; } @SuppressWarnings("all") // 建構函式初始化一個指定容量的順序表 public MyList(int listSize) { t = (T[]) new Object[listSize]; this.length = 0; this.listSize = listSize; } // 向順序表指定位置插入資料插入資料 public int insert(int i, T t) { // 判斷i是否符合條件 if (i < 1 || i > this.length + 1) { // 丟擲一個角標越界異常提示使用者 throw new RuntimeException("輸入的i值不符合,注:i值從1開始"); } // 判斷陣列空間是否充足 if (this.length >= this.listSize) { // 如果不充足重新建立陣列並且把之前陣列中的值複製到新建立的陣列中 @SuppressWarnings("unchecked") T[] tmp = (T[]) new Object[this.listSize + ListConst.LISTINCREMENT]; // 把以前陣列中的數元素複製到這個新建立的陣列 for (int j = 0; j < length - 1; j++) { tmp[j] = this.t[j]; } // 把原陣列指向變長的陣列 this.t = tmp; // 容量增加 this.listSize = this.listSize + ListConst.LISTINCREMENT; } // 把i後面的元素一次後移 for (int j = this.length - 1; j >= i - 1; --j) { this.t[j + 1] = this.t[j]; } // 插入資料 this.t[i - 1] = t; length++; return ListConst.OK; } // 向list元素中新增元素 public void add(T t) { // 從第一個位置開始新增先判斷集合的容量是否充足 if (this.length >= this.listSize) { // 集合容量不充足,通過陣列的複製方法新增容量 // 如果不充足重新建立陣列並且把之前陣列中的值複製到新建立的陣列中 @SuppressWarnings("unchecked") T[] tmp = (T[]) new Object[this.listSize + ListConst.LISTINCREMENT]; // 把以前陣列中的數元素複製到這個新建立的陣列 for (int j = 0; j < length; j++) { tmp[j] = this.t[j]; } // 把原陣列指向變長的陣列 this.t = tmp; // 容量增加 this.listSize = this.listSize + ListConst.LISTINCREMENT; } // 像第一個位置新增元素 this.t[this.length] = t; this.length++; } // 獲取元素 public T get(int i) { // 先判斷傳入的i值是否合理 if (i < 1 || i > this.length) { // 丟擲角標越界異常 throw new RuntimeException("角標越界,不存在該位置的元素"); } // 如果存在該元素 return this.t[i - 1]; } // 移除指定位置的元素 public T remove(int i) { T result; // 判斷i值是否合格 if (i < 1 || i > this.length) { throw new RuntimeException("角標越界,不存在該位置的元素!!!注:i值從1開始"); } result = this.t[i - 1]; for (int j = i; j <= this.length - 1; j++) { this.t[j - 1] = this.t[j]; } this.length--; return result; }
}
package bh.shy.listconst;
public interface ListConst{
int INIT_LIST_SIZE = 10;
int LISTINCREMENT = 10;
int ERROR = 0;
int OK = 1;
}