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?
The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.
asList method returns a type of ArrayList that is different from java. util. ArrayList. The main difference is that the returned ArrayList only wraps an existing array — it doesn't implement the add and remove methods.
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});
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[]>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With