2011-11-06 69 views
1

我有一個HashMap<String,Object>並存儲了來自3種不同類型(整數,字符串,長整數)的一些數據。
如何查找具有特定鍵的值的類型?在java中的HashMap中獲取變量類型

+1

由於您知道期望什麼樣的對象。參見[this](http://stackoverflow.com/questions/106336/how-do-i-find-out-what-type-each-object-is-in-a-arraylistobject)。 – abhinav

回答

1

你可能會重新考慮同一個集合不同類型混爲一談。你失去了泛型的自動類型檢查。

否則,您需要使用instanceof或SLaks建議的getClass來找出類型。

2

它可能是更好地包裝在一個自定義類(如標籤聯合)

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; 
    } 

    //... 
} 

這是更清潔,你可以肯定你會得到什麼

+0

或每種類型的子類型,IFYSWIM。甚至可以添加一些有趣的行爲。 –

+0

取決於他想用它做什麼 –

2

如果你想加工爲主類型。

Object o = map.getKey(key); 
if (o instanceof Integer) { 
.. 
} 

你也可以在一些智能類中封裝值或映射。

1

假設你會做一些事情的結果,你可以嘗試instanceof操作:

if (yourmap.get(yourkey) instanceof Integer) { 
    // your code for Integer here 
} 
2

人們普遍不贊成不必要地使用Object類型。但根據你的情況,你可能必須有HashMap<String, Object>,儘管這是最好的避免。這就是說,如果你必須使用一個,這裏有一小段代碼可能會有所幫助。它使用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 
     } 
    }