简体   繁体   English

Java Hashmap的键入系统是什么?

[英]What is the typing system of Java Hashmap?

I want to store attributes of an entity with a hashmap. 我想用哈希图存储实体的属性。 The value is either an built-in int or a List of String . 该值可以是内置intString List

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. 在阅读了Google提供的各种教程之后,我对地图的键入系统感到困惑。 The closest I came to was something that used String keys and Object values. 我最接近的是使用String键和Object值的东西。


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 . 问题:如何创建Hashmap并插入intList<String>的值,以便在获取值时将其类型转换intList<String> ,而不是intList<String>一个Object

I am depending on Drools Expert package, which accesses values from maps by itself , so the typecasting is not in my control . 我依赖于Drools Expert程序包,该程序包本身会从映射访问值 ,因此类型转换不在我的控制范围内

// Same as attributes.get("jsmith").isValid()
Person( attributes["jsmith"].valid )

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: 您要么使用Map的基本形式来存储值,然后将其作为对象返回,然后您必须自己转换它们:

Object value = map.get(key);

if (value instanceof List<String>) {
    List<String> myList = (List<String>) value;
}

With ints, you can't store the primitive type int, but it will be auto-boxed to an Integer. 使用int,您无法存储基本类型int,但是会将其自动装箱为Integer。 So you would have to check for instanceof Integer, then call .intValue() on the Integer Object. 因此,您必须检查Integer的instanceof ,然后在Integer对象上调用.intValue()

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. 因此,您必须创建一个List<String>属性的映射,以及另一个int属性的映射。

What you are proposing is an example of an algebraic data type . 您要提出的是一个代数数据类型的示例。 Unfortunately, these are not supported in Java. 不幸的是,Java不支持这些功能。

You'll need to use Map and cast the value to either Integer (int), or List yourself. 您需要使用Map并将值强制转换为Integer(int)或列出自己。

In Drools, you can disable the compile time type safety for specific types if you want. 在Drools中,可以根据需要禁用特定类型的编译时类型安全性。 In this case, Drools will work as a dynamically typed language and will resolve the types at runtime for the given type. 在这种情况下,Drools将作为一种动态类型的语言工作,并将在运行时解析给定类型的类型。 Example: 例:

declare Person
    @typesafe(false)
end

rule X
when
    Person( attributes["seniority"] == 7 ) // resolving seniority to Number
...

rule Y
when
    Person( attributes["tags"].size() > 1 ) // resolving tags to List
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM