I want to defined a generic parameter, which should extend Map or Collection, but I don’t know how to do it:
public <T> void test(T t) {}
I can write it as:
public <T extends Map> void test(T t) {}
or
public <T extends Collection> void test(T t) {}
But I don’t know is it possible to let T extend Map or Collection in a single method.
Short answer: no.
What do you intend to do with the
tparameter within the method? SinceMapandCollectionhave onlyObjectas their common supertype, the only methods you can call ontwill be those onObject. (Even methods on both interfaces, such assize(), will be rejected by the compiler.)With that in mind, is there any reason you can’t overload the method in this case? That is, define one implementation for each desired parameter type:
If you don’t want to do that for whatever reason, then it seems that you could equally just declare the method to take
Objectand perform a run-time type check of the class. This is semantically equivalent since you’d have to cast to callMaporCollection-specific methods anyway, though it does mean that the type check is done at compile time instead of runtime. Java’s type system doesn’t let you express this union-type dependency though, so I don’t see any other alternative.