Implement the ArrayList class and methods (from lecture notes) using arrays of objects. If the size of the ArrayList exceeds the size of the array, create a duplicate array with double the size and copy the old array into this new array. You should just implement the ArrayList class and methods (from lecture notes) using arrays of objects. The special change is that the push method should create a duplicate array with double the size and copy the old array into this new array if the size of the ArrayList exceeds the size of the array. public class MyStack { private java.util.ArrayList list = new java.util.ArrayList(); public boolean isEmpty() { return list.isEmpty(); } public int getSize() { return list.size(); } public Object peek() { return list.get(getSize() - 1); } public Object pop() { Object o = list.get(getSize() - 1); list.remove(getSize() - 1); return o; } public void push(Object o) { list.add(o); } public int search(Object o) { return list.lastIndexOf(o); } public String toString() { return "stack: " + list.toString(); } }
Explanation / Answer
//save as MyStack.java :P public class MyStack { private Object[] ary; private int lastObjectPointer; private int size; public MyStack(int capacity){ ary = new Object[capacity]; lastObjectPointer = -1; size = 0; } public boolean isEmpty() { return lastObjectPointer == -1; } public int getSize() { return size; } public Object peek() { return ary[lastObjectPointer]; } public Object pop() { if(size == 0){ return null; } Object o = ary[lastObjectPointer]; ary[lastObjectPointer--] = null; size--; return o; } public void push(Object o) { if(ary.length == size){ Object[] newAry = new Object[2 * ary.length]; for(int i = 0; i