基本上我想要这样的东西:Hashmap<String, String/int>
python相当于java中的字典,因此能够存储键和值对,仅在我的情况下,我需要存储可以是int或字符串的值。例如。我想存储的值(value)是:
{"one":1,
"two":"two"}
因此,它不是在一个键中存储多个值,而是用一种类型的键存储多种类型的值。一种解决方案是使用 Hashmap<String, Object>
并检查 Object
运行时实例,但这确实感觉很棘手,您必须检查所有值。有没有更合适的方法?
最佳答案
没有其他方法可以做到这一点。 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"));
关于java - 映射来存储键和多种类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61052515/