Java Generic Array

Source: Internet
Author: User

Generic array

@author Ixenos

    • Give the conclusion first
      • Cannot (directly) create a generic array
      • The actual run-time object array of a generic array can only be the original type (t[] is object[],pair<t>[]), while the actual runtime array object may be of type T (although the runtime will erase to the original type)
      • General solution: (Generic array wrapper): Use ArrayList to collect object elements of generic array objects, such as arraylist<t>, arraylist<pair<string>>
        • Gets the behavior of the array, and the type safety of the compile period provided by the generic

    • Creating a generic array directly cannot be compiled, whereas a transformed object array is compiled but not run in the JVM
        •  public  class   arrayofgeneric{ static  generic<integer>[] Gia; @SupperssWarnings ( "Unchecked" )  public  static  void   main (string[] args) {gia  = (generic<integer>[]) new  generic[100] ; //! Gia[0] = new  Object (); //  compilation does not pass, cannot (directly) create a generic array instance    
      • The problem is that the array will track their actual type, which is determined when the array is created, so even though Gia has been transformed to generic<integer>[], this information only exists at compile time ( And if there is no @suppresswarning ("unchecked") annotations, you will get a warning of this transformation). At run time, it is still an object array
      • Therefore, the only way to successfully create a generic array is to create a new array of the erased type, and then transform it (and transform it at run time)
        • Cast directly on the entire array, and will still be erased at compile time! So it should be transformed at runtime, and the best way to do this is to use a generic array wrapper to maintain an array of primitive types, type-safe detection (corresponding to return values) and coercion type conversions (which are not important for the runtime) of the element compilation period through the array entry method. thus ensuring type safety.

    • Example of a forced transformation of an entire array (Error method)
    •  Public classGenericarray<t> {    Privatet[] Array; @SupperessWarning ("Unchecked")     PublicGenericarray (intSZ) {Array= (t[])NewObject[sz]; }     Public voidPutintindex, T Item) {Array[index]=item; }     PublicT Get (intIndex) {returnArray[index];}  PublicT[] Rep () {returnArray }//should be at run time export fuss     Public Static voidMain (string[] args) {Genericarray<Integer> Gai =NewGenericarray<integer> (10); //integer[] ia = Gai.rep ();//classcastexceptionobject[] oa = Gai.rep ();//can only return an object array of type object[]
        • The actual runtime object array is object[], while the actual run-time array object may be of type T.

    • Therefore, it should be at runtime, the export of the array object to do the transformation output, the entry method at compile time has been implemented type security, so the export method can be assured that the type conversion, to ensure success. As follows
      •  Public classGenericarray2<t> {    PrivateObject[] Array;//maintain object[] Type array@SupperessWarning ("Unchecked")     PublicGenericArray2 (intSZ) {Array=NewObject[sz]; }     Public voidPutintindex, T Item) {Array[index]=item; }     PublicT Get (intIndex) {return(T) Array[index]; }//Array Object Export strong turn     PublicT[] Rep () {return(t[]) array; }//run-time no matter what is object[] type     Public Static voidMain (string[] args) {Genericarray<Integer> Gai =NewGenericarray<integer> (10); //integer[] ia = Gai.rep ();//still classcastexceptionobject[] oa = Gai.rep ();//can only return an object array of type object[]Gai.put (0,11); System.out.println (Gai.get (0));//11. Successful Export Transformation    }}

  • An array of objects of the actual type type[] is created by reflection at run time, avoiding type erasure, thus converting successfully, without classcastexception
Importjava.lang.reflect.*;  Public classGenericarraywithtypetoken<t> {    Privatet[] Array; @SuppressWarning ("Unchecked")     PublicGenericarraywithtypetoken (class<t> type,intSZ) {Array=(t[]) array.newinstance (type, SZ),//The object array that is actually type type[] is created by reflection at run time, avoids type erasure, thus converting succeeds, no classcastexception} Public voidPutintindex, T Item) {Array[index]=item; }     PublicT Get (intIndex) {returnArray[index];}  PublicT[] Rep () {returnArray;} Can successfully return to the ~ Public Static voidMain (string[] args) {Genericarraywithtypetoken<Integer> GAWTT =NewGenericarraywithtypetoken<> (Integer.class, 10); Integer[] ia=gawtt.rep ();//Can return successfully! }}

    • The run-time class of an array of objects in the ArrayList class is object[], a legacy problem that can be done better, but Java class Library developers are constrained by existing interfaces and cannot modify some Java class library code

Java Generic Array

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.