Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic list return type

I'm having some problems with a method returning a generic list. The code is basically this:

public class MyClass{
    private List<MyListElement> myList = new ArrayList<MyListElement>();

    public <E> List<E> getGenericList(){
        return new ArrayList<E>();
    }

    public void thisWorks(){
        List<MyListElement> newList = getGenericList();
        myList.addAll(newList);
    }

    public void thisDoesntWork(){
        myList.addAll(getGenericList());
    }

    public void thisDoesntWorkEither(){
        for(MyListElement elem : getGenericList()){
            fiddle();
        }
    }
}

Why does the thisDoesntWork() method not work, and is there any other way around it (other than doing it the thisWorks() way which isn't always practical)?

like image 719
MatsT Avatar asked Dec 11 '22 19:12

MatsT


2 Answers

The compiler cannot infer what type to choose for the type parameter <E> of the generic method getGenericList() in thisDoesntWork().

In this case you need to explicitly state the Type for the type argument by calling <MyListElement>getGenericList()

Alternatively you can change the signature of getGenericList() to accept a Class<E> argument. Then you would invoke getGenericList(MyListElement.class) in both thisWorks() and thisDoesntWork(). Admittedly that's a bit more verbose, but definitly more intuitive to clients of your method.

I would say as a general rule, try to make the type arguments of your generic methods be inferrable from that method's arguments.

like image 100
bowmore Avatar answered Dec 14 '22 09:12

bowmore


You can change thisDoesntWork() like so:

  public void thisDoesntWork(){ // well, it works now
      myList.addAll(this.<String>getGenericList());
  }

You need to tell the compiler what type getGenericList() is dealing with.

like image 28
GriffeyDog Avatar answered Dec 14 '22 08:12

GriffeyDog