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 )
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
instanceofInteger, then call.intValue()on theIntegerObject.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.