Why does JAVA not allow the creation of generic arrays?

Source: Internet
Author: User
Tags java keywords

Why does JAVA not allow the creation of generic arrays?

First of all, I think that those who customize java standards can allow java to create generic arrays. They just weigh them and think they are still prohibited. Let's talk about my speculation:

If we write the following code, there is no problem:

List<String> a = new ArrayList<String>();
So why can't we get an array:

List<String>[] arr = new ArrayList<String> [10];
Let's take a look at the differences between the array variable and the common variable: the array variable arr and the common variable a are both in the stack, but that's it! Arr [0] is in the heap. So? So we have the following example:

List<String>[] arr = new ArrayList<String> [10];Object[] orr = arr;List<StringBuffer> buf = new ArrayList<StringBuffer> ();orr[0] = buf;List<String> str = arr[0];String val = str.getValue();
We can find that the first element in the heap is List <StringBuffer>, but arr [0] still points to it. If it is a common variable, this is impossible. Therefore, even if generics are introduced, it is not safe. In the last sentence, the compiler will add string Conversion, resulting in ClassCastException. The generics are intended to be safe. If the array security cannot be guaranteed, why is there another option?

The main reference: http://www.blogjava.net/deepnighttwo/articles/298426.html




Java Generic Array (see Code)

You created a data object instead of an ArrayList object,
Just remove the generic type.
Furthermore, common variable names should be lower-case and should not be the same as java keywords.
Same

Is the array in java generic?

Arrays are not generic classes. I don't have this book! But you can ask more questions.

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.