juztcode
juztcode

Reputation: 1355

java - map to store key and multiple type of values

Basically I'd like something like this: Hashmap<String, String/int> a python equivalent to dictionary in java so be able to store key and value pair, only in my case I need to store the value which can be an int or a string. E.g. of value I'd like to store would be:

{"one":1,
"two":"two"}  

So, it's not storing multiple values in one key, just multiple type of value with one type of key. One solution would be to use Hashmap<String, Object> and check the Object instance at runtime, but that really feels tricky and you'd have to check all the values. Is there a more proper way?

Upvotes: 2

Views: 720

Answers (1)

C&#237;cero Moura
C&#237;cero Moura

Reputation: 2333

There is no another way to do it. "Everything" in Java extends from Object.

You can create a helper class to handle the checking type or even extend HashMap and create your own getValue method, using generics, like following:

public class MyHashMap extends HashMap<String, Object> {

    @Nullable
    public <V> V getValue(@Nullable String key) {
        //noinspection unchecked
        return (V) super.get(key);
    }
}

And using like this:

    MyHashMap map = new MyHashMap();
    map.put("one", 1);
    map.put("two", "two");

    Integer one = map.getValue("one");
    String two = map.getValue("two");

Or even:

 public void printNumber(Integer number){
    // ...
 }

printNumber(map.<Integer>getValue("one"));

Upvotes: 4

Related Questions