Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare HashMap with different types?

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

like image 443
Marcus Toepper Avatar asked Oct 06 '22 21:10

Marcus Toepper


2 Answers

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)
like image 165
Tomasz Nurkiewicz Avatar answered Oct 10 '22 04:10

Tomasz Nurkiewicz


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<?>>.

like image 27
Marko Topolnik Avatar answered Oct 10 '22 03:10

Marko Topolnik