Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force the return type of Arrays.asList

Tags:

java

generics

I have a method returning a collection of a base class:

import java.util.*; class Base { } class Derived extends Base { }  Collection<Base> getCollection() {     return Arrays.asList(new Derived(),                          new Derived()); } 

This fails to compile, as the return type of Arrays.asList (List<Derived>) does not match the return type of the method (Collection<Base>). I understand why that happens: since the generic types are different, the two classes are not related by inheritance.

There are many ways to fix the compiler error from changing the return type of the method to not using Arrays.asList to casting one of the derived objects to Base.

Is there a way to tell the compiler to use a different but compatible type when it resolves the generic type for the Arrays.asList call? (I keep trying to use this pattern and running into this problem, so if there is a way to make it work, I would like to know it.)

I thought that you could do something like

Collection<Base> getCollection() {     return Arrays.asList<Base>(new Derived(),                                new Derived()); } 

When I try to compile that (java 6), the compiler complains that it is expecting a ')' at the comma.

like image 969
Troy Daniels Avatar asked Apr 03 '13 22:04

Troy Daniels


People also ask

What is the return type of arrays asList?

asList returns a fixed-size list that is​ backed by the specified array; the returned list is serializable and allows random access.

Can you modify the collection return by arrays asList ()?

Using Arrays. Arrays. asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it.

Are asList arrays immutable?

Arrays. asList() , the list is immutable.

What does arrays asList () do?

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.


1 Answers

Your syntax is almost correct; the <Base> goes before the method name:

return Arrays.<Base>asList(new Derived(),                            new Derived()); 

Java 8

For Java 8, with its improved target type inference, the explicit type argument is not necessary. Because the return type of the method is Collection<Base>, the type parameter will be inferred as Base.

return Arrays.asList(new Derived(),                      new Derived()); 

The explicit type parameter is still necessary for Java 7 and below. You can still supply the explicit type parameter in Java 8; it's optional.

like image 84
rgettman Avatar answered Sep 23 '22 04:09

rgettman