Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 confirm this.

like image 973
ada Avatar asked Dec 13 '10 09:12

ada


1 Answers

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();
like image 63
Jon Skeet Avatar answered Sep 20 '22 02:09

Jon Skeet