5

I have a function, declared like this:

public synchronized void update(HashMap<String, Comparable> data)

data contains strings and ints, but the Comparable gives a warning

Comparable is a raw type. References to generic type Comparable<T> should be 
 parameterized

As I'm not overly found of warnings, question is, is there a correct way, I don't want to suppress the warning.

Thank in advance! Marcus

Marcus Toepper
  • 2,403
  • 4
  • 27
  • 42
  • A Comparable is for a specific type. You can't compare cross data types. That's why the warning asks you to restrict your Comparable to a specific type. – asgs Aug 19 '12 at 07:21

2 Answers2

3

This should please the compiler:

public synchronized void update(HashMap<String, Comparable<Object>> data)

Object being the most specific supertype of both String and Integer. Also there is space for improvement in your code. First of all rely on Map interface, not on concrete HashMap implementation. Secondly if you don't really need the Comparable functionality, just use Map<String, Object>. Last but not least, avoid multi-type collections and prefer strong typing.

"[...]data contains strings and ints[...]" - if it's just a map from String to Integer:

public synchronized void update(HashMap<String, Integer> data)
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

First of all, you shouldn't insist on a HashMap in your signature. Why not just a Map? Second, you should allow the map value type be anything implementing Comparable. Third, the Comparable itself can be parameterized with an unbounded wildcard:

void update(Map<String, ? extends Comparable<?>> data)

Now you can call it with any of HashMap<String, Integer>, TreeMap<String, String> or SortedMap<String, Comparable<?>>.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436