这一部分先简单描述一下数组的特性以及对数组的增删查等操作。
数组的大小固定,所以对于增加元素,只要数组空间中有空的位置就可以将要添加的元素添加进去。
对于数组元素的删除,删除对应位置的元素后,要将删除位用后面的元素填充。
一、无序数组
无序数组是只在数组空间中,元素是按照插入顺序排列的,而不是按照元素之间的大小来排列。无序数组相对于有序数组而言,在插入的效率上要高,但是在查找的效率上要低。
代码如下:
1 public class LowArray { 2 private static final double BASIC_VALUE = 0; 3 private double[] basicArray; 4 5 public LowArray(int initialCapacity) { 6 this.basicArray = new double[Math.max(initialCapacity, 0)]; 7 } 8 9 public void setElements(int index, double value) { 10 this.checkIndex(index); 11 this.basicArray[index] = value; 12 } 13 14 public double getElements(int index) { 15 this.checkIndex(index); 16 return this.basicArray[index]; 17 } 18 19 public boolean deleteElementsByIndex(int index) { 20 this.checkIndex(index); 21 int len = this.basicArray.length - 1; 22 for (int i = index; i < len; i++) { 23 this.basicArray[i] = this.basicArray[i + 1]; 24 } 25 this.basicArray[len] = BASIC_VALUE; 26 return true; 27 } 28 29 public boolean deleteElements(double value) { 30 boolean result = false; 31 int len = this.basicArray.length; 32 for (int i = 0; i < len; i++) { 33 if (Double.compare(this.basicArray[i], value) == 0) { 34 result = this.deleteElementsByIndex(i); 35 if (result) { 36 break; 37 } 38 } 39 } 40 41 if (result) { 42 this.deleteElements(value); 43 } 44 return false; 45 } 46 47 public void show() { 48 System.out.println(Arrays.toString(this.basicArray)); 49 } 50 51 private void checkIndex(int index) { 52 if (index > this.basicArray.length) { 53 throw new IllegalArgumentException("index is error,index:=" + index + ", length:=" + this.basicArray.length); 54 } 55 } 56 }