OnJava8-Examples/generics/GenericArray.java

23 lines
633 B
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/GenericArray.java
public class GenericArray<T> {
private T[] array;
@SuppressWarnings("unchecked")
public GenericArray(int sz) {
array = (T[])new Object[sz];
}
public void put(int index, T item) {
array[index] = item;
}
public T get(int index) { return array[index]; }
// Method that exposes the underlying representation:
public T[] rep() { return array; }
public static void main(String[] args) {
2015-05-05 11:20:13 -07:00
GenericArray<Integer> gai = new GenericArray<>(10);
2015-04-20 15:36:01 -07:00
// This causes a ClassCastException:
//! Integer[] ia = gai.rep();
// This is OK:
Object[] oa = gai.rep();
}
} ///:~