1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| public class MyArray {
private int[] array; private int size;
public MyArray(int capacity) { this.array = new int[capacity]; size = 0; }
public void insert(int index, int element) throws Exception { if (index < 0 || index > size) { throw new IndexOutOfBoundsException("超出数组实际元素范围!"); } if (size >= array.length) { resize(); } for (int i = size - 1; i >= index; i--) { array[i + 1] = array[i]; } array[index] = element; size++; }
public void resize() { int[] arrayNew = new int[array.length * 2]; System.arraycopy(array, 0, arrayNew, 0, array.length); array = arrayNew; }
public int delete(int index) throws Exception { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("超出数组实际元素范围!"); } int deletedElement = array[index]; for (int i = index; i < size - 1; i++) { array[i] = array[i + 1]; } size--; return deletedElement; }
public void output() { for (int i = 0; i < size; i++) { System.out.println(array[i]); } }
public static void main(String[] args) throws Exception { MyArray myArray = new MyArray(4); myArray.insert(0, 3); myArray.insert(1, 7); myArray.insert(2, 9); myArray.insert(3, 5); myArray.insert(1, 6); myArray.insert(5, 8); myArray.delete(3); myArray.output(); } }
|