简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM