Skip to content
Advertisement

trouble initialize List Using Arrays.asList

When I initialize List, I am able to do this:

JavaScript

But when I want to simplify it using Arrays.asList:

JavaScript

It cannot compile with error:

JavaScript

Why it cannot do the type inference right and how to fix this?

Advertisement

Answer

Remember that ... is just syntactic sugar for an array parameter. You can call a method with a variadic parameter foo(Object...) either using

JavaScript

or

JavaScript

since the compiler constructs the second form anyway.

Because the receiver type isn’t considered when the compiler infers types, it looks at Arrays.asList(new Object[]{"bar", 286}) and thinks that you mean to create a list of Object, not a singleton list of Object[].

The easiest way with your existing syntax is just to add an explicit type parameter:

JavaScript

Adding the <Object[]> tells the compiler what T should be.

Or, if you don’t need the list to be mutable:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement