I have a HashMap<String,Object>
and stored some data from 3 different types (Integer,String,Long).
How Can I find out what is the type of a value with a specific key?

- 14,760
- 31
- 112
- 175
-
1Since you know what kind of objects to expect. See [this](http://stackoverflow.com/questions/106336/how-do-i-find-out-what-type-each-object-is-in-a-arraylistobject). – abhinav Nov 06 '11 at 19:12
6 Answers
It is generally frowned upon to use the Object
type unnecessarily. But depending on your situation, you may have to have a HashMap<String, Object>
, although it is best avoided. That said if you have to use one, here is a short little snippet of code that might be of help. It uses instanceof
.
Map<String, Object> map = new HashMap<String, Object>();
for (Map.Entry<String, Object> e : map.entrySet()) {
if (e.getValue() instanceof Integer) {
// Do Integer things
} else if (e.getValue() instanceof String) {
// Do String things
} else if (e.getValue() instanceof Long) {
// Do Long things
} else {
// Do other thing, probably want error or print statement
}
}

- 325
- 3
- 12
You can call the getClass
method to find the type of an object:
map.get(key).getClass()

- 868,454
- 176
- 1,908
- 1,964
it might be better to wrap it in a custom class (like a tagged union)
class Union{
public static enum WrappedType{STRING,INT,LONG;}
WrappedType type;
String str;
int integer;
long l;
public Union(String str){
type = WrappedType.STRING;
this.str=str;
}
//...
}
this is cleaner and you can be sure what you get

- 47,288
- 5
- 68
- 106
-
Or subtypes for each type, IFYSWIM. Could even have some interesting behaviour added. – Tom Hawtin - tackline Nov 06 '11 at 19:25
-
If you want to make processing based on type.
Object o = map.getKey(key);
if (o instanceof Integer) {
..
}
You could also encapsulate value or map(s) in some smart class.

- 1,277
- 10
- 16
You might reconsider lumping together different types in the same collection. You lose the automatic typechecking from generics.
Otherwise, you'll need to use instanceof or as SLaks suggested getClass to find out the type.

- 744
- 4
- 17
Assuming that you will do something with the result, you could try the instanceof
operator:
if (yourmap.get(yourkey) instanceof Integer) {
// your code for Integer here
}

- 83,810
- 28
- 209
- 234

- 36
- 4