Is this a limitation with Generics in Java?

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 will not compile ( cannot resolve symbol T ). If I replaced the class declaration as follows:

 public class CollectionAttribute<E extends Collection<?>> 

Then I can not refer to the parameterized type of the collection.

Am I missing something or have reached the generic limit in Java?

+7
java generics
source share
2 answers

You need to add a second general 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 cannot write value.add(T) .

+13
source share

There are two problems with your example class. First, you need to declare what T means, which means it must be included in Generics for the class or be a real class type. In this case, you probably want

 public class CollectionAttribute<T, E extends Collection<T>> 

The second problem you would probably find if you got the compiler past the first is that the body of the addValue method is trying to add the type T to the collection, and not this value:

 public void addValue(T value) { this.value.add(value); } 
+7
source share

All Articles