开发者

Is there a dictionary which accepts values of various data types?

I need a map where the values are of different types, like integer, string etc. The problem with Java is that primitives here are not Objects which suggests that it may not be possible to have a hybrid dictionary. I want to con开发者_JS百科firm this.


It sounds like you just want a Map<String, Object> (or whatever your key type is).

Primitive values will be boxed appropriately:

Map<String, Object> map = new HashMap<String, Object>();

map.put("int", 20);
map.put("long", 100L);
// etc

Note that in order to retrieve the value and unbox it, you have to mention the specific wrapper 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();


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

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

then you can use primitives of type int, as they will be auto-boxed into an Integer.

As for your original question, defining a Map as such:

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

then you should be able to put any Java object in the map.


You could exploit autoboxing and use Integer instead of int and so forth.

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


You can use Integer instead of int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜