Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trouble initialize List<Object[]> Using Arrays.asList

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?

like image 603
qqibrow Avatar asked Oct 06 '16 06:10

qqibrow


People also ask

What is arrays asList ()?

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.

Is arrays asList same as ArrayList?

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.


2 Answers

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});
like image 75
Andy Turner Avatar answered Oct 06 '22 22:10

Andy Turner


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[]>.

like image 20
Eran Avatar answered Oct 07 '22 00:10

Eran