null
null

Reputation: 1433

Reuse generic type T extending a specific class

I'd like to use an ArrayList that contains elements of the type specified by the class.

public class Foo<T extends Comparable<T>> extends AbstractFoo {

    private ArrayList<T> list =  new ArrayList<T>();

    @Override
    public void add(Comparable e) {
        list.add(e); // The method add(T) in the type ArrayList<T> is not applicable for the arguments (Comparable)
    }
}

Why can't I add e to list? As T definitely extends Comparable, I suppose I can add e to list.

Upvotes: 2

Views: 190

Answers (2)

Tim
Tim

Reputation: 43314

Because all Ts are Comparable, but not all Comparables are Ts you cannot add a Comparable to a list of T.

You can do it by having a ArrayList<Comparable<T>> though

public class Foo<T extends Comparable<T>> extends AbstractFoo {

    private ArrayList<Comparable<T>> list =  new ArrayList<>();

    @Override
    public void add(Comparable e) {
        list.add(e); 
    }
}

Upvotes: 1

Calculator
Calculator

Reputation: 2789

Let's assume you have a class Teacher and a class Student which both implement Comparable. Now if you create a Foo<Teacher>, this foo object will contain a list of teachers ArrayList<Teacher>. If your code would compile, you now could add a student (because it is comparable) to the teacher list, which is of course not allowed.

You might actually want:

@Override
public void add(T e) {
    list.add(e); 
}

Upvotes: 2

Related Questions