-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStack.java
More file actions
63 lines (50 loc) · 1.18 KB
/
Copy pathStack.java
File metadata and controls
63 lines (50 loc) · 1.18 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
51
52
53
54
55
56
57
58
59
60
61
62
63
package effect.java.generics.item31;
import java.util.Arrays;
import java.util.Collection;
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 void pushAll(Iterable<? extends E> src) {
for(E e: src) {
push(e);
}
}
public void popAll(Collection<? super E> dst) {
while(!isEmpty()) {
dst.add(pop());
}
}
public static void main(String[] args) {
Stack <Number> numberStack = new Stack<>();
Iterable<Integer> integers = null;
numberStack.pushAll(integers);
Collection<Object> objects = null;
numberStack.popAll(objects);
}
}