OnJava8-Examples/generics/GenericCast.java

30 lines
769 B
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/GenericCast.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
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]; }
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
public class GenericCast {
public static final int SIZE = 10;
public static void main(String[] args) {
FixedSizeStack<String> strings =
2015-05-05 11:20:13 -07:00
new FixedSizeStack<>(SIZE);
2015-04-20 15:36:01 -07:00
for(String s : "A B C D E F G H I J".split(" "))
strings.push(s);
for(int i = 0; i < SIZE; i++) {
String s = strings.pop();
System.out.print(s + " ");
}
}
} /* Output:
J I H G F E D C B A
*///:~