user2066880
user2066880

Reputation: 5034

Java: Recursive generics compiler error

Given the following contrived example:

public class Child extends Parent<Child, String> () {}

public class Parent<E extends Parent, V> {

    public V value;

    // maps <List of Entities> to <List of Values>
    public List<V> filterValues(List<E> entities) {
        List<V> values = new ArrayList();
        for (E entity : entities) {
            values.add(entity.value); // compiler error: add(V) cannot be
                                      // applied to (java.lang.Object)
        }
        return values;
    }

}

I don't fully understand the nature of this error. Is List<V> resolving to List<Object>? How can I solve my problem of mapping a specific type to its associated field?

Upvotes: 0

Views: 69

Answers (2)

Dima
Dima

Reputation: 40500

If I understand correctly what you are trying to do, it seems that you want to declare Parent as class Parent<E extends Parent<?,V>, V>.

It will compile, but without knowing the purpose of this design it is hard to further comment on its usefulness. My "gut feeling" is that you are seriously overthinking it ... One immediate thought is why not parametrize filterValues with E instead of the entire class:

class Parent<V> {
     public <E extends Parent<V>> List<V> filterValues(List<E> entities) {
         ....
      }
}

Upvotes: 5

jacobm
jacobm

Reputation: 14025

public class Parent<E extends Parent, V> bounds E with Parent which is a raw type. When you access any method or field of entity, then, because it has type E which is bounded by an erased type, you get the erased type for Parent; in particular V is Object. Hence the error.

Upvotes: 1

Related Questions