2

I've a read only method that should be able to take either

1. Map<Date, List<X>>

or

2. Map<Date, List<Y>>

as a parameter.

Here, I've the following two options to define the method.

A. private <T> List<Date> myMethod(Map<Date, List<T>> map)
B. private List<Date> myMethod(Map<Date, List<?>> map)

Both work fine for me, which one is preferable?

Thanks.

2 Answers 2

5

The first one gives you access to the T type in case you need that (for example, if you need to cast something to type T or something like that). With the latter, you simply state that you don't give a damn what sort of elements that List contains.

Sign up to request clarification or add additional context in comments.

6 Comments

I see, so if I don't give a damn about the value set, I might as well declare my method as myMethod(Map<Date, ?>) right?
Yes, if you don't even care whether the values are lists or not.
@ManishMulani: if later you find that X and Y have some common interface/ancestor you could restrict your accepted generic to <T extends CommonInterface>. If you really only accept those types is because of something they have in common, and other types don't have. So it makes sense.
@MichaelLaffargue: You're right, I removed my malicious side note :)
@ManishMulani: if you don't care about the value types I recommend the ?. It decouples your method (managing a Map<Date, ?>) from the fact that you have values of type List. The less your method needs to know to make its job (in a correct way), the better.
|
5

From JLS

<T> boolean addAll(Collection<T> c)

This version is sufficiently flexible, but note that the type parameter is used only once in the signature. This reflects the fact that the type parameter is not being used to express any kind of interdependency between the type(s) of the argument(s), the return type and/or throws type. In the absence of such interdependency, generic methods are considered bad style, and wildcards are preferred.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.