trouble initialize List Using Arrays.asList

Tags: , ,



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

List<Object[]> foo = new ArrayList<>();
foo.add(new Object[]{816, "foo", 2.6});

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

List<Object[]> bar = Arrays.asList(new Object[]{"bar", 286});

It cannot compile with error:

incompatible types: inference variable T has incompatible bounds
equality constraints: java.lang.Object[]
lower bounds: java.lang.Object

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

Answer

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

foo("hello", 1);

or

foo(new Object[]{"hello", 1});

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:

List<Object[]> bar = Arrays.<Object[]>asList(new Object[]{"bar", 286});

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

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

List<Object[]> bar = Collections.singletonList(new Object[]{"bar", 286});


Source: stackoverflow