-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathGenericStack.java
More file actions
50 lines (38 loc) · 1.11 KB
/
GenericStack.java
File metadata and controls
50 lines (38 loc) · 1.11 KB
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
package StackArray;
import java.util.Arrays;
/**
* Expand the ArrayList implementation of stack here to use an E[] array. Still implement push, pop, and isEmpty.
* Remember, you might need to resize the stack in the push method.
*
* @param <E>
*/
public class GenericStack<E> {
private E[] elements;
public GenericStack() {
elements = (E[]) new Object[0];
}
public E push(E aThing) {
E[] temp = Arrays.copyOf(elements, elements.length + 1);
temp[elements.length] = aThing;
elements = temp;
return aThing;
}
public E pop() throws IndexOutOfBoundsException {
E poppedObj = elements[elements.length - 1];
if (elements.length > 0) {
E[] temp = Arrays.copyOf(elements, elements.length - 1);
for (int i = 0; i < elements.length - 1; i++) {
temp[i] = elements[i];
}
elements = temp;
}
return poppedObj;
}
public boolean isEmpty() {
if (elements.length > 0) {
return false;
} else {
return true;
}
}
}