2

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?

3
  • 1
    Not really! As a rule of thumb, and unless really important, you should use members of one type as a value in a Collection. The closest you can do is to use <String, String> but that comes with its own challenges: How do you know if "1" is String or Integer? Commented Apr 6, 2020 at 3:38
  • Why can't the second pair just be a String... 1 can be converted to a String. Commented Apr 6, 2020 at 3:38
  • @Prashant , good point, but, I insert these values to a database so I just knew it could either be a textual data or a digit, but this is another challenge Commented Apr 6, 2020 at 3:41

1 Answer 1

4

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"));
Sign up to request clarification or add additional context in comments.

2 Comments

the problem with this is, you can't use key/value pair in a loop since you have to pass in <dataType> generic parameter. I was basically thinking of using that so as to loop through the schema and value pair otherwise I'd have to either sync two arrays or define the schema everytime
You can do it like this: for (Map.Entry<String, Object> entry : map.entrySet()){ map.getValue(entry.getKey()); } Once HashMap.get(key) is O(1).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.