trouble initialize List<Object[]> Using Arrays.asList
When you pass an array of reference types to Arrays.asList
you get a List
of that reference type.
Therefore Arrays.asList(new Object[]{"bar", 286})
returns a List<Object>
, not a List<Object[]>
.
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});
If your list only has one element in it, Collections.singletonList(new Object[] {...})
is a better choice, as it avoids varargs and makes the behavior more obvious at the call site.