Java array covariance

Source: Internet
Author: User

In some cases, even if an object is not a base type of an array, we can assign it to an array element. This property is called covariant (covariance). Covariance can be used under the following conditions:

An array is an array of reference types.

There is an implicit or explicit conversion between an assigned object type and an array base type.

Since there is always an implicit conversion between a derived class and a base class, it is always possible to assign an object of a derived class to an array declared for the base class.

Only the array exists covariant, this function is advantageous also has the disadvantage, relative to the list is supports the generic type does not support the covariance

Class a{

}

Class B extends a{

}

a[] array = new B[10];

a[] array = new A[10];

Array[0] = new B ();

This type creates an array or assigns a success that is the covariance reason of the array

For list

list<a> list = new Arraylist<b> ();(compilation failed, generic)

It is because the array supports covariance that it leads to the following pitfalls

object[] array = new INTEGER[10]; Array[0] = "s String";

Compile normal

Run the report exception

Exception in thread "main" java.lang.ArrayStoreException:java.lang.StringAt Com.me.test.Main.main (main.java:9)

So it's reasonable to use the covariance of arrays

Java array covariance

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.