"Thinkinginjava" 37, about generic arrays

Source: Internet
Author: User

/*** 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.