StephanM StephanM - 19 days ago 5
Java Question

Java: List initialization with Generics (T extends Enum<T> & AnyInterface)

im still quite weak in using generics and im having a question:
Based on the following method i would like to initalize a list:

public <T extends Enum<T> & AnyInterface> boolean getIsDescSort(Class<T> tableSortEnum) {
return tableSortEnum.getName().endsWith(DESC_SUFFIX);
}


Is it (in general) possible to initialize a List exactly with these kinds of objects? Or in other words: Can i type my list with these informations? Enums which implement a certain interface?

List<T extends Enum<T> & AnyInterface> myList;


shows me several errors in my Eclipse IDE so i assume it wouldn't compile.
I read some articles about this but don't get if this is even allowed/possible while initialze a collection...

Answer

You're trying to type at the wrong place. For example the following will work just fine

public class Foo<T extends Enum<T> & AnyInterface> {
    private List<T> foo;
}

As will this

public static <T extends Enum<T> & AnyInterface> List<T> foo(Class<T> clazz) {
    ArrayList<T> foo = new ArrayList<>();
    return foo;
}