Java Hashmap 的类型系统是什么?
我想用哈希图存储实体的属性。该值可以是内置 int
或 String
的 List
。
name : "John Smith"
attributes:
"seniority" : (int) 7
"tags" : List<String>("asst_prof","cs_dept")
"another_attrib" : (int) 3
在阅读了 Google 提供的不同教程后,我对地图的打字系统感到困惑。我最接近的是使用 String
键和 Object
值的东西。
问题:如何创建 Hashmap 并插入 int
或 List
的值,以便当我获取值时,它是类型转换(标识为类型成员)为 int
或 List
,而不是 Object
。
我依赖 Drools Expert 包,它 自行从地图访问值,因此类型转换不在我的控制范围内。
// Same as attributes.get("jsmith").isValid()
Person( attributes["jsmith"].valid )
I want to store attributes of an entity with a hashmap. The value is either an built-in int
or a List
of String
.
name : "John Smith"
attributes:
"seniority" : (int) 7
"tags" : List<String>("asst_prof","cs_dept")
"another_attrib" : (int) 3
I am confused about the typing system of the Map, after reading diverging tutorials Google gives. The closest I came to was something that used String
keys and Object
values.
Question: How do I create a Hashmap and insert values of int
or List<String>
, so that when I fetch the value, it is typecast (identified as a member of type) as either an int
or a List<String>
, not an Object
.
I am depending on Drools Expert package, which accesses values from maps by itself, so the typecasting is not in my control.
// Same as attributes.get("jsmith").isValid()
Person( attributes["jsmith"].valid )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能。要么使用 Map 的基本形式将值作为对象存储和返回,然后您必须自己转换它们:
使用 int 时,您无法存储原始类型 int,但它将自动装箱为 Integer。因此,您必须检查
instanceof
Integer,然后在Integer
对象上调用.intValue()
。要获得作为对象返回的对象,您必须使用泛型,但不能混合类型。因此,您必须创建一个
List
属性的映射和另一个 int 属性的映射。You can't. Either you use the basic form of Map that stores and returns the values as Objects, then you have to cast them yourself:
With ints, you can't store the primitive type int, but it will be auto-boxed to an Integer. So you would have to check for
instanceof
Integer, then call.intValue()
on theInteger
Object.To get the Objects returned as the Objects they are then you have to use Generics, but you can't mix types. So you would have to create a Map of
List<String>
attributes and another for int attributes.您提议的是代数数据类型的示例。不幸的是,Java 不支持这些。
您需要使用 Map 并将值转换为 Integer (int) 或自己的 List。
What you are proposing is an example of an algebraic data type. Unfortunately, these are not supported in Java.
You'll need to use Map and cast the value to either Integer (int), or List yourself.
在 Drools 中,如果需要,您可以禁用特定类型的编译时类型安全性。在这种情况下,Drools 将作为动态类型语言工作,并将在运行时解析给定类型的类型。例子:
In Drools, you can disable the compile time type safety for specific types if you want. In this case, Drools will work as a dynamically typed language and will resolve the types at runtime for the given type. Example: