-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathObjectStack.java
More file actions
46 lines (38 loc) · 1.19 KB
/
ObjectStack.java
File metadata and controls
46 lines (38 loc) · 1.19 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
package StackArray;
import java.util.Arrays;
/**
* Expand the ArrayList implementation of stack here to use an Object[] array. Still implement push, pop, and isEmpty.
* Remember, you might need to resize the stack in the push method.
* @param <E>
*/
public class ObjectStack<E> {
private Object[] elements;
public ObjectStack() {
this.elements = new Object[0];
}
public Object push(Object item) {
this.elements = Arrays.copyOf(this.elements, this.size()+ 1);
this.elements[this.size() - 1] = item;
return item;
}
public Object pop() {
Object oldValue = this.elements[this.size() -1];
int numMoved = size() - this.size() - 1;
if (numMoved > 0)
System.arraycopy(this.elements, this.size() + 1, this.elements, this.size(),
numMoved);
this.elements = Arrays.copyOf(this.elements, this.size() -1);
return oldValue;
}
public boolean isEmpty() {
for(Object element: this.elements) {
if (element != null) {
return false;
}
}
return true;
}
public int size() {
return this.elements.length;
}
}