我想要一個方法參數來定義HashMap將接受的類。沿着線的東西:Java - 使用方法參數定義HashMap類型
private HashMap hashMap = new HashMap();
public boolean createMap(Object obj) {
return hashMap = new HashMap<String, obj.getClass()>() != null;
}
我想要一個方法參數來定義HashMap將接受的類。沿着線的東西:Java - 使用方法參數定義HashMap類型
private HashMap hashMap = new HashMap();
public boolean createMap(Object obj) {
return hashMap = new HashMap<String, obj.getClass()>() != null;
}
你不能做你想要做的:你不能「定義類HashMap
將接受」,因爲在運行時HashMap
將接受所有類。
你可以做什麼,而另一方面,就是:
private Map<String, ?> map;
public <V> void createMap(Class<V> clazz) {
map = Collections.checkedMap(new HashMap<String, V>(),
String.class, clazz);
}
...將實際執行你想創建的限制,與反思。在這種情況下,您的hashMap
成員的類型應該是Map<String, Object>
,雖然它會強制
定義類型的功能,接受你的願望是價值的地圖
public <T> Map<String, T> checkedStringKeyMap(Class<T> type) {
return Collections.checkedMap(new HashMap<String, T>(), String.class, type);
}
然後創建自己的地圖如下
類型Map<String, Person> persons = checkedStringKeyMap(Person.class);
'public boolean createMap(){return hashMap = new HashMap ()!= null; }'?你嘗試過你的例子嗎?你收到的錯誤是什麼? –
crush
此方法將始終返回'true' – hoaz
@crush:它需要'>'而不是().getClass – Wolfizen