我想用 HashMap 存储实体的属性。该值是内置 int
或List
的String
.
name : "John Smith"
attributes:
"seniority" : (int) 7
"tags" : List<String>("asst_prof","cs_dept")
"another_attrib" : (int) 3
在阅读了 Google 提供的不同教程后,我对 map 的输入系统感到困惑。我最接近的是使用 String
的东西键和Object
值(value)观。
问题:如何创建 HashMap 并插入 int
的值或List<String>
,这样当我获取该值时,它类型转换(标识为类型的成员)为 int
或List<String>
,不是 Object
.
我依赖 Drools Expert 包,它 accesses values from maps by itself ,所以类型转换不在我的控制范围内。
// Same as attributes.get("jsmith").isValid()
Person( attributes["jsmith"].valid )
最佳答案
你不能。要么使用 Map 的基本形式将值作为对象存储和返回,然后您必须自己转换它们:
Object value = map.get(key);
if (value instanceof List<String>) {
List<String> myList = (List<String>) value;
}
使用 int 时,您无法存储原始类型 int,但它会自动装箱为 Integer。所以你必须检查 instanceof
整数,然后调用.intValue()
关于Integer
对象。
要获取按对象本身返回的对象,您必须使用泛型,但不能混合类型。所以你必须创建一个 List<String>
的 map 属性和 int 属性。
关于java - Java Hashmap 的类型系统是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9275046/