4

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?

Ariyan
  • 14,760
  • 31
  • 112
  • 175
  • 1
    Since 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 Answers6

6

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
        }
    }
CarManuel
  • 325
  • 3
  • 12
5

You can call the getClass method to find the type of an object:

map.get(key).getClass()
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

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

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
2

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.

viktor
  • 1,277
  • 10
  • 16
1

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.

Chip McCormick
  • 744
  • 4
  • 17
1

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
}
NullUserException
  • 83,810
  • 28
  • 209
  • 234
gustavogp
  • 36
  • 4