Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Declaring variables with multiple generic "constraints" on them

Tags:

java

generics

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

like image 215
H. Guckindieluft Avatar asked Feb 01 '11 09:02

H. Guckindieluft


People also ask

Can a generic class have multiple constraints?

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.

Can a generic class have multiple generic parameters Java?

A Generic class can have muliple type parameters.

How do you declare a generic variable in Java?

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.

Can generics take multiple type parameters?

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.


1 Answers

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;
like image 67
Sean Patrick Floyd Avatar answered Oct 14 '22 22:10

Sean Patrick Floyd