資料結構-00 陣列(無序陣列)
阿新 • • 發佈:2019-01-26
1、用long[ ] 模擬
package org.gzw.arr; public class MyArray { private long[] arr; /* 有效資料的長度 */ private int elements; public MyArray() { arr = new long[50]; } public MyArray(int maxSize) { arr = new long[maxSize]; } /** * 新增資料 */ public void insert(long value){ arr[elements] = value; elements++; } /** * 顯示資料 */ public String display(){ StringBuffer strbuf = new StringBuffer(); strbuf.append("[ "); /*for(long l : arr){ strbuf.append(l + ", "); }*/ for(int i =0; i<elements;i++){ strbuf.append(arr[i] + ", "); } strbuf.delete(strbuf.length()-1, strbuf.length()); strbuf.append("]"); return strbuf.toString(); } /** * 查詢資料,並返回位置索引 */ public int search(long value){ int i; for(i=0;i<elements;i++){ if(arr[i] == value) break; } if(i==elements){ return -1; }else{ return i; } } /** * 查詢資料,更具索引來查 */ public long get(int index){ if(0<=index && index<elements){ return arr[index]; }else{ throw new ArrayIndexOutOfBoundsException(); } } /** * 刪除資料 */ public void delete(int index){ if(0<=index && index<elements){ for(int i=index;i<elements;i++){ if(i<elements-1){ arr[i] = arr[i+1]; }else break; } elements--; }else{ throw new ArrayIndexOutOfBoundsException(); } } /** * 更新資料 */ public void change(int index, long value){ if(0<=index && index<elements){ arr[index] = value; }else{ throw new ArrayIndexOutOfBoundsException(); } } }
2、測試
package org.gzw.arr; public class TestMyArray { public static void main(String[] args) { MyArray myArr = new MyArray(6); myArr.insert(1); myArr.insert(139); myArr.insert(229); myArr.insert(9); myArr.insert(19); myArr.insert(39); System.out.println(myArr.display()); System.out.println(myArr.search(229)); System.out.println(myArr.search(88)); System.out.println(myArr.get(2)); //System.out.println(myArr.get(-1)); myArr.delete(2); System.out.println(myArr.display()); myArr.change(1, 888); System.out.println(myArr.display()); } }