OnJava8-Examples/generics/GenericArray.java

24 lines
673 B
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/GenericArray.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
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:
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) {
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();
}
} ///:~