2015-04-20 15:36:01 -07:00
|
|
|
|
//: generics/GenericArrayWithTypeToken.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-04-20 15:36:01 -07:00
|
|
|
|
import java.lang.reflect.*;
|
|
|
|
|
|
|
|
|
|
public class GenericArrayWithTypeToken<T> {
|
|
|
|
|
private T[] array;
|
|
|
|
|
@SuppressWarnings("unchecked")
|
|
|
|
|
public GenericArrayWithTypeToken(Class<T> type, int sz) {
|
|
|
|
|
array = (T[])Array.newInstance(type, sz);
|
|
|
|
|
}
|
|
|
|
|
public void put(int index, T item) {
|
|
|
|
|
array[index] = item;
|
|
|
|
|
}
|
|
|
|
|
public T get(int index) { return array[index]; }
|
|
|
|
|
// Expose the underlying representation:
|
2015-05-18 23:05:20 -07:00
|
|
|
|
public T[] rep() { return array; }
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
GenericArrayWithTypeToken<Integer> gai =
|
2015-05-05 11:20:13 -07:00
|
|
|
|
new GenericArrayWithTypeToken<>(
|
2015-04-20 15:36:01 -07:00
|
|
|
|
Integer.class, 10);
|
|
|
|
|
// This now works:
|
|
|
|
|
Integer[] ia = gai.rep();
|
|
|
|
|
}
|
|
|
|
|
} ///:~
|