"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Can\'t Arrays Hold Generic Items in Java?

Why Can\'t Arrays Hold Generic Items in Java?

Published on 2024-11-18
Browse:642

Why Can\'t Arrays Hold Generic Items in Java?

Can Arrays Hold Generic Items?

Generic types and arrays can interact differently in Java. Consider the following code:

ArrayList a = new ArrayList();

This code compiles successfully, creating a generic ArrayList named a. However, the following code fails to compile:

ArrayList[] a = new ArrayList[10];

Why is this? It appears that arrays and generics are incompatible. To understand this, let's explore Type Erasure in Java.

Type Erasure: Behind the Scenes

When Java compiles, it performs Type Erasure, which replaces generic type information with raw types (Object). This prevents errors like placing a String into an ArrayList of Integers. However, arrays require a raw type, and generics cannot be represented as raw types.

Fixing the Array Issue

To create an array of generic items, you can explicitly cast the array to the desired type:

ArrayList[] a = (ArrayList[]) new ArrayList[10];

This cast instructs the compiler that the array should be considered an array of ArrayLists with Key elements.

List of Lists: The Exception

In Java, a list of lists is not considered an array. Hence, the following code compiles without type casting:

ArrayList> b = new ArrayList>();

This distinction arises because ArrayList is a non-array type.

Conclusion

Arrays and generic types have limitations in Java due to Type Erasure. However, by explicitly casting arrays to the desired generic type or using lists of lists, one can navigate these limitations and effectively use generic types in both contexts.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3