-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathStack.java
More file actions
38 lines (28 loc) · 942 Bytes
/
Stack.java
File metadata and controls
38 lines (28 loc) · 942 Bytes
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
package StackArrayList;
import java.util.ArrayList;
/**
* Implement Stack<E> by adding the push, pop, and isEmpty functions. It must pass the prewritten unit tests.
* If you pop on an empty stack, throw an IndexOutOfBoundsException.
*/
public class Stack<E> {
private ArrayList<E> elements;
// private Object the;
public Stack() {
elements = new ArrayList();
}
// pushes the object to top of stack. works like add method but to the front instead of end
public void push(E item) {
int index = 0;
elements.add(index, item);
}
public boolean isEmpty() {
return elements.size() == 0;
}
public E pop()throws IndexOutOfBoundsException {
if(elements.isEmpty()) throw new IndexOutOfBoundsException("this list is empty");
int index = 0;
E removedObject = elements.get(0);
elements.remove(index);
return removedObject;
}
}