James Armstrong
James Armstrong

Reputation: 600

Proper type signature for a list of a generic types?

Am I forced to use rawtypes in my situation, or is there some kind of signature I can apply to my type declarations that will eliminate them entirely? I have a generic interface that is implemented by one or more classes. Here is a reduced form of the relevant code.

public class Event { ... }

public interface Processor<E extends Event> {
  void process(List<E> events);
}

public class ProcessorImpl<E extends Event> implements Processor<E> {
  @Override
  public void process(List<E> events) { ... }
}

So the above are the relevant classes, now I will illustrate my confusion.

public class SomeApp {
  public List<Processor> processors; // rawtype of Processor<E extends Event>
  public List<Event> events;

  public SomeApp(...) { ... } // Fills the lists up

  public void run() {
    for (int i = 0; i < processors.size(); ++i) {
      processors.get(i).process(events); // takes a list of <E extends Event>
    }  
  }
}

All of this code compiles and runs properly in my particular case, however I want to avoid using raw types if I can. I've experimented with wildcard bounds in the lists for the Processor type i.e List<Processor<? extends Event>>, but that always leads me to needing to change the process method to take a wildcard type rather than the generic E, and that seems to defeat the purpose of having the generics in that class.

Upvotes: 0

Views: 101

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

You can simply make SomeApp generic as well with a type that extends Event then use that type to parameterize the events and processors Lists.

public class SomeApp <T extends Event> {
    public List<Processor<T>> processors; 
    public List<T> events;

Upvotes: 1

Related Questions