Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a limitation with Generics in Java?

Tags:

java

generics

I want to define the following class as such:

public class CollectionAttribute<E extends Collection<T>> {
    private String name;
    private E value;
    public CollectionAttribute(String name, E value) {
        this.name = name;
        this.value = value;
    }

    public E getValue() { return value; }

    public void addValue(T value) { value.add(T); }
}

This won't compile (cannot resolve symbol T). If I replace the class declaration with the following:

public class CollectionAttribute<E extends Collection<?>>

Then I can't reference the parametrized type of the collection.

Am I missing something or have I reached a limitation with generics in Java ?

like image 912
Two Shoes Avatar asked Jun 10 '10 17:06

Two Shoes


1 Answers

You need to add a second generic parameter for T:

public class CollectionAttribute<T, E extends Collection<T>> {
    private String name;
    private E values;
    public CollectionAttribute(String name, E values) {
        this.name = name;
        this.values = values;
    }

    public E getValue() { return value; }

    public void addValue(T value) { values.add(value); }
}

As Nathan pointed out, you also can't write value.add(T).

like image 78
SLaks Avatar answered Sep 23 '22 09:09

SLaks