/*** book: "Thinking in Java" * function: Because of the erase, the array when the operation of the type can only be object[]. If we transform it immediately to t[], the actual type of the array will be lost at compile time, while the compiler may miss some potential error checking. So we'd better use object[[inside the collection], and then when you use the array element, add a transformation to T. * File: genericarray2.java* time: April 19, 2015 09:38:19* Author: Cutter_point*/package Lesson15_generices;public class Genericarray2<t>{private object[] array;//constructor, creating a certain length of generic array public GenericArray2 (int sz) {array = new Object[sz] ;//The type created is an object of type}//assign a value to the location specified in the array public void put (int index, T item) {Array[index] = Item;} Gets the value of the specified position @suppresswarnings ("unchecked") public T get (int index) {return (T) array[index];//one by one, one by one. However, an array should not be fetched, and the Java array should be saved as an object of type}//get this generic @suppresswarnings ("unchecked") public t[] Rep () {return (t[]) array; public static void Main (string[] args) {//Create a 10-bit array genericarray2<integer> gai = new genericarray2<integer> (10);//Put 1 to 10for (int i = 0; i <; ++i) Gai.put (i, I), for (int i = 0; i <) ++i) System.out.print (Gai.get (i) + ""); System.out.println ();//Remove this array try{integer ia[] = Gai.rep ();//Call this function, this is stillTry it object[] convert to t[], this is not correct} catch (Exception e) {e.printstacktrace ();}}}
Output:
0 1 2 3 4 5 6 7 8 9
Java.lang.ClassCastException: [Ljava.lang.Object; Cannot is cast to [Ljava.lang.Integer;
At Lesson15_generices. Genericarray2.main (genericarray2.java:55)
"Thinkinginjava" 37, about generic arrays