简体   繁体   English

java - map 存储键和多种类型的值

[英]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.基本上我想要这样的东西: Hashmap<String, String/int> a python 相当于 java 中的字典所以能够存储键和值对,只有在我的情况下我需要存储可以是 int 或一个字符串。 Eg 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.一种解决方案是使用Hashmap<String, Object>并在运行时检查Object实例,但这确实感觉很棘手,您必须检查所有值。 Is there a more proper way?有没有更合适的方法?

There is no another way to do it.没有其他方法可以做到这一点。 "Everything" in Java extends from Object. Java 中的“一切”从 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:您可以创建一个助手 class 来处理检查类型,甚至扩展 HashMap 并使用 generics 创建自己的 getValue 方法,如下所示:

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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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