Home > Java > javaTutorial > Why Can\'t I Create Generic Arrays in Java?

Why Can\'t I Create Generic Arrays in Java?

Susan Sarandon
Release: 2024-10-28 22:15:31
Original
603 people have browsed it

 Why Can't I Create Generic Arrays in Java?

Generic Arrays in Java

Arrays and generics create a programming roadblock in Java. You can't create an array of parametric types directly. This is because arrays are covariant, meaning they retain the type of their elements at runtime, while generics use type erasure.

A workaround is to use Array.newInstance() like this:

private Comparable[] hashtable;

...

hashtable = (Comparable[])Array.newInstance(Comparable.class, tableSize);
Copy after login

However, it's important to note that this solution is not ideal.

Why not use generic arrays?

  • Arrays are covariant, but generics are not.
  • This means that an array of a supertype is not necessarily an array of the subtype.
  • For example, an Object[] array is not necessarily a Comparable[] array.

To avoid these issues, it's recommended to use an ArrayList instead of an array when working with generics. ArrayLists are covariant and type-safe, which makes them a better choice for storing generic types.

For a more detailed explanation, refer to the Java Generics FAQ:

Can I create an array whose component type is a concrete parameterized type?

No, because it is not type-safe.

Arrays are covariant, which means that an array of supertype references is a supertype of an array of subtype references. That is, Object[] is a supertype of String[] and a string array can be accessed through a reference variable of type Object[].

The above is the detailed content of Why Can\'t I Create Generic Arrays in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template