java – 用于存储键和多种类型值的映射

huangapple go评论86阅读模式
英文:

java - map to store key and multiple type of values

问题

基本上我想要类似这样的东西:Hashmap<String, String/int>,这在Python中相当于Java中的字典,可以存储键值对。不过在我这种情况下,我需要存储值,这个值可以是整数或者字符串。例如,我想要存储的值会是:

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

所以,不是在一个键中存储多个值,而是在一个类型的键中存储多种类型的值。一个解决方案是使用Hashmap<String, Object>,然后在运行时检查Object实例,但这确实感觉有些棘手,你需要检查所有的值。有没有更合适的方法呢?

英文:

Basically I'd like something like this: Hashmap&lt;String, String/int&gt; 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:

{&quot;one&quot;:1,
&quot;two&quot;:&quot;two&quot;}  

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&lt;String, Object&gt; 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?

答案1

得分: 4

没有另一种方法可以做到这一点。
在Java中,“一切”都是从Object继承的。

您可以创建一个辅助类来处理类型检查,甚至可以扩展HashMap并创建自己的getValue方法,使用泛型,如下所示:

public class MyHashMap extends HashMap<String, Object> {
    
    @Nullable
    public <V> V getValue(@Nullable String key) {
        //noinspection unchecked
        return (V) super.get(key);
    }
}

然后像这样使用:

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

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

甚至可以这样使用:

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

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

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&lt;String, Object&gt; {
    
    @Nullable
    public &lt;V&gt; V getValue(@Nullable String key) {
        //noinspection unchecked
        return (V) super.get(key);
    }
}

And using like this:

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

    Integer one = map.getValue(&quot;one&quot;);
    String two = map.getValue(&quot;two&quot;);

Or even:

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

printNumber(map.&lt;Integer&gt;getValue(&quot;one&quot;));

huangapple
  • 本文由 发表于 2020年4月6日 11:27:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/61052515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定