0

When should one of these be preferred to another?

public static void doStuffWithIt_A( Map<Integer,  ? extends Object > theThings){ ...} 
public static void doStuffWithIt_B( Map<Integer,  ?                > theThings){ ...} 
public static void doStuffWithIt_C( Map<Integer,  Object           > theThings){ ...} 

I've been using a variable parameters passing interface in java, inspired by python's "**kw"argument syntax, and I'm trying to get it 'more right'

Matt S.
  • 878
  • 10
  • 21
  • [This](https://stackoverflow.com/questions/3486689/java-bounded-wildcards-or-bounded-type-parameter?rq=1) might help. Also, I wouldn't use either the first or third form, because it's not helpful. – saiarcot895 Jun 19 '14 at 01:47
  • Depends on what you want to do with it. I wouldn't go for the first one though. – awksp Jun 19 '14 at 01:48
  • @saiarcot895 The third form could in fact be helpful. If you want to stick things into the map the first and second options are pretty much useless, but the third one is OK. – awksp Jun 19 '14 at 01:48
  • @user3580294: Ah. I assumed Java would treat `?` as an `Object` or a subclass of `Object`. – saiarcot895 Jun 19 '14 at 01:49
  • @saiarcot895 You're pretty much right, but because of that there are some subtleties. `?` by itself means *anything*, but because of that (and the fact that Java's generics are invariant) the only thing you'd be able to put into the first two options is `null` because *what* that "anything" is, the compiler doesn't know. – awksp Jun 19 '14 at 01:50
  • 1
    Also see http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs – kapex Jun 19 '14 at 01:50

1 Answers1

3

By using Object, the first and the second option are effectively the same thing. There are significant differences between those 2 and the 3rd option, however. Consider those calling the methods. If one has a Map<Integer, String>, you could call the first 2, but not the 3rd option. From within the method itself, only the 3rd option would allow for the method to insert data into the Map (without resorting to dropping the generic definition and - optionally - casting the arg).

Brett Okken
  • 6,210
  • 1
  • 19
  • 25
  • It seems the best proxy for python's "**kw" argument syntax is that 3rd option then (and then dealing with the casting). – Matt S. Jun 19 '14 at 02:33
  • @user3580294 That simply is not true. Consider the following options: `Map arg1; Map map = arg1; map.put(3, "5");` or `Map arg1; Map map = arg1; Map castedMap = (Map map; map.put("4", "8");` – Brett Okken Jun 19 '14 at 02:39
  • Er, is assigning a generic map to a raw type reference considered casting? Didn't know that was considered casting. I was thinking the "normal" `()` kind of casting on the stuff you were going to put in, not the map itself. My mistake. And now that I reread what you said, I see that I was reading it wrong. My apologies. – awksp Jun 19 '14 at 02:55