forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericCast.java
More file actions
31 lines (29 loc) · 912 Bytes
/
GenericCast.java
File metadata and controls
31 lines (29 loc) · 912 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
// generics/GenericCast.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.stream.*;
class FixedSizeStack<T> {
private int index = 0;
private Object[] storage;
public FixedSizeStack(int size) {
storage = new Object[size];
}
public void push(T item) { storage[index++] = item; }
@SuppressWarnings("unchecked")
public T pop() { return (T)storage[--index]; }
}
public class GenericCast {
public static final int SIZE = 10;
public static void main(String[] args) {
FixedSizeStack<String> strings =
new FixedSizeStack<>(SIZE);
Stream.of("A B C D E F G H I J".split(" "))
.forEach(s -> strings.push(s));
for(int i = 0; i < SIZE; i++)
System.out.print(strings.pop() + " ");
}
}
/* Output:
J I H G F E D C B A
*/