Some limitations of Java generics

Source: Internet
Author: User

This article mainly refers to the Java Programming Idea (4th edition) of the Java Generic section, only as a simple reading notes.

In contrast to C + + generics, Java generics are just a wiping mechanism during compilation. This is due to a compromise that is considered in the light of previous compatibility. In the compiled generic code, all the generic information is erased during compilation, so no information about the generic parameter types can be obtained. So list<string> and list<integer> are actually the same type.

Refer to the following code:

    The following 3 examples fail to compile public    <T> void Testgeneric (Object arg) {        if (arg instanceof T) {}    //1        t var = new T ();             2        t[] array = new t[100];//3    }

As you can see from the above code, the limitations of this wiping mechanism include the following:

1. instanceof cannot be used

2. Cannot instantiate generic class

3. Cannot instantiate a generic array

The main reason why the above 3 methods cannot be compiled is that the generic wipe mechanism wipes out the specific type information and cannot know the exact type information at run time. However, Java provides another way to circumvent these limitations.

Resolution 1

For the 1th type, the instanceof syntax cannot be used, and we can take advantage of the Dynamic isinstance ():

    Testinstance (String.class, "abc") = = True public    static <T> Boolean testinstance (class<t> C, Object ARG) {        return c.isinstance (ARG);    } <
Resolution 2

For the 2nd type, you cannot instantiate a generic class, and if you have an parameterless default constructor for the generic class to instantiate, we can take advantage of the class object:

    public static <T> T Creategeneric (class<t> c) {        T x = null;        try {            x = c.newinstance ();        } catch (Exception e) {            throw new RuntimeException (e);//creategeneric<integer .class> throws an exception because the integer has no default constructor        }        return x;     }
since the code above has some limitations with class object instantiation, we can also use the factory method to display the corresponding class:

    Interface Genericfactory<t> {        T create ();    }        Class Integerfactory implements genericfactory<integer> {        @Override public        Integer Create () {            return new Integer (0);        }    }
Resolution 3

For the 3rd type, the generic array cannot be instantiated, but we can use arraylist<t> instead, but if we must get the behavior of the array and the security type of the compile period provided by the generics,

    Genericarray ga = new genericarray<integer> (ten);    Ga.put (3, ten);    int abc = (Integer) ga.get (3);    Integer[] AAA = (integer[]) Ga.array (); Throw classcastexception    class Genericarrayex<t> {        private t[] array;        public Genericarray (int size) {            array = (t[]) new object[size];        }        public void put (int index, T item) {            Array[index] = Item;        }        Public T get (int index) {            return array[index];        }        Public t[] Array () {            return array;        }    }
for the above code, we use a Genericarray class to wrap, but the inside is actually a object[] object array, in the put and get when the compile check, but the problem comes, if we use Array () Method attempts to obtain an internal array and transforms it, it throws classcastexception, because the array is actually a object[] Object! In order to solve this problem, we can use array.newinstance.

    Genericarrayex ga = new genericarrayex<integer> (Integer.class, ten);    Ga.put (3, ten);    int abc = (Integer) ga.get (3);    Integer[] AAA = (integer[]) Ga.array (); Can successfully transform    class Genericarrayex<t> {        private t[] array;        Public Genericarrayex (class<t> type, int size) {            array = (t[]) array.newinstance (type, size);        }        public void put (int index, T item) {            Array[index] = Item;        }        Public T get (int index) {            return array[index];        }        Public t[] Array () {            return array;        }    }
in this way, you can use t[].


Some limitations of Java generics

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.