Java Generic Array

Source: Internet
Author: User

Reprinted from http://blog.csdn.net/orzlzro/article/details/7017435

Java does not support generic arrays. Other words

list<string>[] ls = new arraylist<string>[10];

is not supported, and

list<string>[] ls = new ARRAYLIST[10]

But you can.

It was clear from Sun's document that a situation was mentioned:

list<string>[] LSA = new list<string>[10]; Not really allowed. Object o = lsa;object[] oa = (object[]) o; list<integer> li = new arraylist<integer> (); Li.add (New Integer (3)); oa[1] = Li; Unsound, but passes run time store checkstring s = lsa[1].get (0); Run-time error:classcastexception.

In this case, because of the JVM generic erasure mechanism, the JVM is not aware of the generic information at runtime, so it is possible to assign a arraylist<integer> to oa[1] without appearing arraystoreexception, However, when the data is taken to do a type conversion, so there will be classcastexception, if you can make a generic array of declarations, the above-mentioned situation in the compilation period will not have any warnings and errors, only when the runtime error. Instead of restricting the declaration of a generic array, it is much better to have a type-safety problem with the code at compile time than to have no hint.

For the above reasons, Java does not support declaring generic arrays, more precisely: the type of an array cannot be a type variable, unless it is in the form of a wildcard , see the following example:

list<?>[] LSA = new list<?>[10]; OK, array of unbounded wildcard type. Object o = lsa;object[] oa = (object[]) o; list<integer> li = new arraylist<integer> (); Li.add (New Integer (3)); oa[1] = Li; correct.string s = (String) lsa[1].get (0); Run time error, but cast is explicit.

Because of the way the wildcard is done, the final fetch of the data is to do an explicit type conversion, so there is no problem with the previous example.

Java Generic Array

Related Article

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.