2015-09-07 11:44:36 -06:00
|
|
|
// generics/GenericCast.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2017-01-20 21:30:44 -08:00
|
|
|
import java.util.*;
|
2016-01-25 18:05:55 -08:00
|
|
|
import java.util.stream.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
class FixedSizeStack<T> {
|
2017-01-20 21:30:44 -08:00
|
|
|
private final int size;
|
2015-06-15 17:47:35 -07:00
|
|
|
private Object[] storage;
|
2017-01-20 21:30:44 -08:00
|
|
|
private int index = 0;
|
2017-05-01 14:33:10 -06:00
|
|
|
FixedSizeStack(int size) {
|
2017-01-20 21:30:44 -08:00
|
|
|
this.size = size;
|
2015-06-15 17:47:35 -07:00
|
|
|
storage = new Object[size];
|
|
|
|
}
|
2017-01-20 21:30:44 -08:00
|
|
|
public void push(T item) {
|
|
|
|
if(index < size)
|
|
|
|
storage[index++] = item;
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
@SuppressWarnings("unchecked")
|
2017-01-20 21:30:44 -08:00
|
|
|
public T pop() {
|
|
|
|
return index == 0 ? null : (T)storage[--index];
|
|
|
|
}
|
|
|
|
@SuppressWarnings("unchecked")
|
|
|
|
Stream<T> stream() {
|
|
|
|
return (Stream<T>)Arrays.stream(storage);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
public class GenericCast {
|
2017-01-20 21:30:44 -08:00
|
|
|
static String[] letters =
|
|
|
|
"ABCDEFGHIJKLMNOPQRS".split("");
|
2015-06-15 17:47:35 -07:00
|
|
|
public static void main(String[] args) {
|
|
|
|
FixedSizeStack<String> strings =
|
2017-01-20 21:30:44 -08:00
|
|
|
new FixedSizeStack<>(letters.length);
|
|
|
|
Arrays.stream("ABCDEFGHIJKLMNOPQRS".split(""))
|
|
|
|
.forEach(strings::push);
|
|
|
|
System.out.println(strings.pop());
|
|
|
|
strings.stream()
|
|
|
|
.map(s -> s + " ")
|
|
|
|
.forEach(System.out::print);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2017-01-20 21:30:44 -08:00
|
|
|
S
|
|
|
|
A B C D E F G H I J K L M N O P Q R S
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|