Design Dynamic Array (Resizable Array) Solution
class DynamicArray{ private ArrayList<Integer> arrayList; private int capacity; public DynamicArray(int capacity){ if(capacity <=0){ throw new IllegalArgumentException("Capacity must be greater than 0."); } this.arrayList = new ArrayList<>(capacity); this.capacity = capacity; } public int get(int i){ if(i<0 || i>= arrayList.size()){ throw new IllegalArgumentException("Index is out of bounds."); } return arrayList.get(i); } public void set(int i, int n){ if(i<0 || i>= arrayList.size()){ throw new IllegalArgumentException("Index is out of bounds."); } arrayList.set(i, n); } public void pushback(int n){ if(arrayList.size() == capacity){ resize(); } arrayList.add(n); } public int popback(){ if(arrayList.isEmpty()){ throw new IllegalStateException("ArrayList is empty"); } int lastIndex = arrayList.size() - 1; int poppedElement = arrayList.get(lastIndex); arrayList.remove(lastIndex); return poppedElement; } private void resize(){ capacity *= 2; ArrayList<Integer> newArray = new ArrayList<Integer>(capacity); newArray.addAll(arrayList); arrayList = newArray; } public int getSize(){ return arrayList.size(); } public int getCapacity(){ return capacity; } }
Leave a Comment