OnJava8-Examples/generics/GenericArrayWithTypeToken.java

24 lines
700 B
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/GenericArrayWithTypeToken.java
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();
}
} ///:~