我確實對我的應用程序有很多角色。如何在java中定義KeyPairValue中的值
private static HashMap<String, String> doctorcredentials = new HashMap<String, String>("doctor","Test1234!");
它引發我錯誤,以消除參數。每次我只需要添加此憑據。無法直接定義?
我確實對我的應用程序有很多角色。如何在java中定義KeyPairValue中的值
private static HashMap<String, String> doctorcredentials = new HashMap<String, String>("doctor","Test1234!");
它引發我錯誤,以消除參數。每次我只需要添加此憑據。無法直接定義?
由於documentation沒有構造可以從收集比現有的地圖等
public HashMap(Map<? extends K,? extends V> m)
以滿足新的HashMap的正確方法是增加對逐個創建新實例後創建HashMap
private static HashMap<String, String> doctorcredentials = new HashMap<String, String>();
doctorcredentials.put("doctor","Test1234!");
//etc...
無論如何,你可以創建一個工廠類,將爲你創建HashMaps - 類似
//You need to add casting exception handling, no argument situation etc...
public class HashMapFactory<T, V> {
public HashMap<T, V> create(Object... arg) {
HashMap<T, V> map = new HashMap<T, V>();
for(int i = 1; i < arg.length; i+=2) {
map.put((T)arg[i-1], (V)arg[i]);
}
return map;
}
}
然後你可以使用這個喜歡
HashMapFactory<String, String> factory = new HashMapFactory<String, String>();
HashMap<String, String> map = factory.create("one", "two", "three", "four", "five", "six");
System.out.println(map.get("five"));
HashMap中沒有一個構造函數來支持你指定的參數。請參考documentation
爲了把值HashMap中使用的情況下
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
按照規定,我認爲要做到這一點:
private static HashMap<String, String> doctorcredentials = new HashMap<String, String>();
doctorcredentials.put("doctor","Test1234!");
,你可以簡單地聲明自己的地圖是這樣的:
private static HashMap<String, String> doctorcredentials = new HashMap<String, String>() {
{
put("doctor","Test1234!");
}
};
爲了幫助人們回答您的問題,您需要更加具體地瞭解錯誤。請編輯您的帖子,以便將編譯[mcve]時的確切錯誤(最好使用複製+粘貼以避免轉錄錯誤)。 –