Java陣列的簡單實現
阿新 • • 發佈:2019-01-30
Java將陣列封裝為類的簡單實現
public class Array { private long[] array; private int length = 0; //構造 public Array(int size) { array = new long[size]; } //插入,增加陣列長度 public void insert(long item) { array[length++] = item; } // 查詢 public boolean find(long item) { for (int i = 0; i < length; i ++) { if (array[i] == item) { return true; } } return false; } // 查詢返回下標或-1 public int indexOf(long item) { for (int i = 0; i < length; i ++) { if (array[i] == item) { return i; } } return -1; } //刪除元素並移動陣列 public boolean delete(long item) { int i = 0; for (i = 0; i < length; i++) { if (item == array[i]) { break; } } if (i == length) return false; for (int j = i; j < length - 1; j++) { array[j] = array[j + 1]; } length--; return true; } // 列印陣列 public void show() { System.out.print("["); for (int i = 0; i < length; i++) { if (i == length -1) System.out.print(array[i]); else { System.out.print(array[i] + ", "); } } System.out.print("]\n"); } public static void main(String[] args) { Array array = new Array(10); array.insert(1); array.insert(3); array.insert(2); array.show(); System.out.println(array.length); int index = array.indexOf(2); if (array.find(2) && index != -1) System.out.println("找到了"); else System.out.println("沒找到"); if (array.delete(2)) System.out.println("刪除了"); else System.out.println("沒找到"); } }