I have a bunch of classes in java that all implement an interface called IdObject (specifying a getId() method). Moreover, they also all implement Comparable<> with themselves as type parameter, so they are all comparable to themselves.
What I'd like to do is declare a list of such objects, fill it, then sort it and call getId() on them. So my code looks like this:
List<? extends IdObject & Comparable<?>> objectList = null;
if (foo) {
objectList = new ArrayList<TypeA>();
...
} else if (bar) {
objectList = new ArrayList<TypeB>();
...
}
if (objectList != null) {
Collections.sort(objectList);
for (IdObject o : objectList) {
System.out.println(o.getId());
}
}
Basically my problem lies in the first line -- I want to specify two "constraints" for the type because I need the first one to make sure I can print the ID in the loop and the second one to make sure I can use Collections.sort() on the list.
The first line does not compile.
Is there a way to make this work without specifying a generic type without type parameters and using unchecked operations? I could also not find an example of this on the internet.
Greetings
There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.
A Generic class can have muliple type parameters.
A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.
Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
List<? extends IdObject & Comparable<?>>
This type of multiple bounded type parameters is only possible in class and method signatures, I'm afraid.
So I guess the closest you can get is to define an interface:
public interface MyInterface extends IdObject, Comparable<MyInterface>
And declare your list like this:
List<? extends MyInterface> objectList = null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With