Madbreaks Madbreaks - 1 month ago 10
Java Question

Implement generic method with List parameter

I'm trying to define and then implement an abstract setter which takes a List of Objects as a parameter. Here's the gist of this simple idea:

public abstract class MyClass {
public abstract void setThings(List<?> things);
}

public class Bar extends MyClass {
private List<String> things;

@Override
public void setThings(List<String> things) {
this.things = things;
}
}


That doesn't work. I get
Method does not override method from its superclass
and
both methods have the same erasure, but neither overrides the other
. I understand the latter error relating to erasures, but even so I can't figure out the correct way to do this. I've tried some others like:

public abstract <T> void setThings(List<T> things);


...as well as a few others. And I've found other questions/answers on SO that come close to addressing this, but none that have provided a solid answer (at least not that was clear to me). I've read through the tutorials as well to no avail. What am I missing?

Answer

So Java is quite correctly telling you that you haven't implemented the abstract method setThings which takes a List<?> not a List<T> or List<String>. All of these are different things. See this question for a detailed explanation.

The simplest solution is to introduce a generic for your abstract class as well:

public abstract class MyClass<T> {
    public abstract void setThings(List<T> things);
}

public class SubClass extends MyClass<String> {
    private List<String> things;

    public void setThings(List<String> things) {
        this.things = things;
    }
}