我想讓Map對象包含特定的值類型。帶自定義值對象的地圖
Map<String,Object> foo = new HashMap<String,Object>();
foo.put("1",new Integer(1));
foo.put("2", new String("hello"):
for (Map.Entry<Integer, Integer> entry : foo.entrySet()) {
if(entry.getValue() instanceof String) {
//do something
}
else if(entry.getValue() instanceof Double) {
//throw Exception
}
}
你可以看到我想要完成的。我需要特定的值類型在我的地圖對象,所以我不必把大量的if/else語句。我如何做到這一點?
然後,您將爲每個地圖創建不同的地圖。您不能將'Integer'和'String'放在同一個Map中,而不會將地圖概括爲Object類型。 –
使用幾張地圖。或者使用所有值類型通用的接口。請注意,'new String(「hello」)'沒有多大意義。只需使用「你好」。 –
你可以使用'case'語句... – SomeKittens