英文:
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<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?
答案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<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"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论