Why does Java not let you create a generic array

Source: Internet
Author: User

First of all, I think those who have customized Java standards can have Java create generic arrays, but they weigh it out and think it's a good thing to do, just say my guess:

If we write the following code is no problem:

List<string> a = new arraylist<string> ();
Well, that's why the array doesn't work:

list<string>[] arr = new arraylist<string> [10];
Let's take a look at the difference between an array variable and a normal variable: the array variable arr and the normal variable A are all in the stack, but! Arr[0] 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 ();
It can be found that the No. 0 element in the heap is list<stringbuffer>, but Arr[0] still points to it, if it is a normal variable, it is not possible, so even if the introduction of generics, is not safe; the last sentence, because the compiler adds a string conversion , resulting in classcastexception, generics are meant to be safe, if the security of the array is not guaranteed, why are there superfluous?

This paper mainly refer to: http://www.blogjava.net/deepnighttwo/articles/298426.html



Why does Java not let you create a 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.