-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStack.java
More file actions
52 lines (41 loc) · 975 Bytes
/
Copy pathStack.java
File metadata and controls
52 lines (41 loc) · 975 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package effect.java.generics.item29;
import java.util.Arrays;
import java.util.EmptyStackException;
public class Stack<E> {
private E[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
@SuppressWarnings("unchecked")
public Stack() {
elements = (E[])new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(E e) {
ensureCapacity();
elements[size++] = e;
}
public E pop() {
if (size ==0) {
throw new EmptyStackException();
}
E result = elements[--size];
elements[size] = null;
return result;
}
private void ensureCapacity() {
if(elements.length == size) {
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
public boolean isEmpty() {
return size == 0;
}
public static void main(String[] args) {
Stack <String> stack = new Stack<>();
for(String arg: args) {
stack.push(arg);
}
while(!stack.isEmpty()) {
System.out.println(stack.pop().toUpperCase());
}
}
}