Generic Array Creation Error
Question:
When attempting to create an array of generic classes using an expression like:
public static ArrayList[] a = new ArrayList [2];
Java reports a "Generic array creation" error. Why is this not allowed?
Answer:
Java arrays do not support generics. Specifically, the Java Virtual Machine (JVM) verifies bytecode to ensure that generic array types are not declared. This is because allowing generic arrays would introduce the potential for runtime conversion errors, known as the "erasure problem."
Alternative Solutions:
Use a Collection Instead:
Create an Auxiliary Class:
Avoid Unchecked Conversions:
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