DynamicArray.java
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);
}
}