Is there a dictionary that accepts the values ​​of various data types?

I need a map where the values ​​are of different types, such as integer, string, etc. The problem with Java is that the primitives here are not Object , which suggests that a hybrid dictionary may not be possible. I want to confirm this.

+6
java dictionary types primitive-types map
source share
4 answers

It sounds like you just need Map<String, Object> (or any other type of your key).

Primitive values ​​will be appropriately inserted into the box:

 Map<String, Object> map = new HashMap<String, Object>(); map.put("int", 20); map.put("long", 100L); // etc 

Note that in order to retrieve a value and delete it, you must specify a specific shell type:

 // Explicit unboxing int x = (int) (Integer) map.get("int"); // Implicit unboxing int y = (Integer) map.get("int"); // USing a method from Number instead int z = ((Integer) map.get("int")).intValue(); 
+8
source share

When you put primitives in a Map in Java, they get Auto-Boxed in their object form. For example, if you have a Map , which is defined as:

 Map<Integer, String> myMap = new HashMap<Integer, String>(); 

then you can use int primitives, as they will be automatically placed in Integer .

Regarding your initial question defining Map as such:

 // using Integer for key type, can be something else Map<Integer, Object> myMap = new HashMap<Integer, Object>(); 

then you can place any Java object on the map.

+3
source share

You can use autoboxing and use Integer instead of int, etc.

The corresponding types ( Integer , Double , Bool , ...) inherit the object, so you can use the standard Map<Object, Whatever> and throw arbitrary things at it.

+1
source share

You can use Integer instead of int .

0
source share

All Articles