Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse - why infer generic suggested for Java's array

You cannot create arrays of parameterized types, so this code in Eclipse

ArrayList<Integer>[] list = new ArrayList[1];

Can't be parameterized , but Eclipse shows a warning

Type safety: The expression of type ArrayList[] needs unchecked conversion to conform to ArrayList<Integer>[]

And also shows suggestion Infer Generic Type Arguments which does nothing when submitted.

Infer Generic Type Arguments Replaces raw type occurrences of generic types by parameterized types after identifying all places where this replacement is possible.

Should this suggestion be removed or am I missing something?

like image 424
user7294900 Avatar asked Dec 13 '18 07:12

user7294900


People also ask

What are generic arrays in Java and why are they useful?

Java allows generic classes, methods, etc. that can be declared independent of types. However, Java does not allow the array to be generic. The reason for this is that in Java, arrays contain information related to their components and this information is used to allocate memory at runtime.

What is infer generic type arguments?

Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned.

Why generic arrays are not allowed?

If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.

Is generic array creation allowed in Java?

You can't have arrays of generic classes. Java simply doesn't support it. and then create an array of MyObjectArrayList .


1 Answers

Yes, the suggestion should be removed. It is not possible to replace the raw type with a parameterized type here, because an array creation expression must use a reifiable type as the component type. It's illegal to do new ArrayList<Integer>[1]. You can only do new ArrayList[1] or new ArrayList<?>[1], both of which will produce a warning in order to convert to type ArrayList<Integer>[] (the second one will require an explicit cast which produces an unchecked cast warning).

like image 151
newacct Avatar answered Oct 19 '22 17:10

newacct