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 |
import java.util.Arrays; public class DynamicArray{ private int[] arr; private int count = 0; private boolean debug = true; public DynamicArray(int initialSize){ arr = new int[initialSize]; } public void add(int element){ if (count == arr.length) expandArray(); arr[count++] = element; } private void expandArray(){ if (debug) System.out.println("Expanding array from " + arr.length + " to " + arr.length *2); int[] arr2 = new int[arr.length * 2]; for (int i = 0; i < arr.length; i++){ arr2[i] = arr[i]; } arr = arr2; } /* Insert element at index in arr. - If index < 0 or index > count, throw IndexOutOfBoundsException - If count == arr.length, expand array - If index < count shift elements right from count to index */ public void insert(int index, int element){ if (index < 0 || index > count) throw new IndexOutOfBoundsException(); if (count == arr.length) expandArray(); for (int j = count; j > index; j--){ arr[j] = arr[j-1]; } arr[index] = element; count++; } public int get(int index){ if (index < 0 || index >= count) throw new IndexOutOfBoundsException(); return arr[index]; } public String toString(){ return String.join(", ", Arrays.stream(arr) .limit(count) .mapToObj(String::valueOf) .toArray(String[]::new)); } // Testing public static void main(String[] args){ DynamicArray da = new DynamicArray(2); da.add(5); da.add(12); da.add(7); da.insert(1, 3); da.insert(0, 4); da.insert(5, 10); System.out.println("get idx 3 " + da.get(3)); System.out.println(da); } } |