如何使用String
來指定特定的HashMap
。使用帶有hashmaps的字符串
如:
public static ConcurrentHashMap<String, Integer> age = new ConcurrentHashMap<String, Integer>();
String s = "age";
s.get("Nick");
如何使用String
來指定特定的HashMap
。使用帶有hashmaps的字符串
如:
public static ConcurrentHashMap<String, Integer> age = new ConcurrentHashMap<String, Integer>();
String s = "age";
s.get("Nick");
如果你想一個人的名字映射到自己的年齡,你需要
Map<String,Integer> age = new HashMap<>(); // only use ConcurrentHashMap if you intend
// to use that Map from multiple threads
...
age.put("Nick",42);
...
int nicksAge = age.get("Nick");
public class HashMapTest {
public static HashMap<String, Integer> ageMap = new HashMap<String, Integer>();
public static void main(String[] args) {
ageMap.put("Nick", 12);
Integer age = ageMap.get("Nick");
System.out.println(age);
}
}
你可以做到這一點使用泛型
https://docs.oracle.com/javase/tutorial/java/generics/
泛型允許您指定地圖的類型。因此,而不是使用
public static ConcurrentHashMap age = new ConcurrentHashMap();
你可以使用
public static Map<String, Short> age = new ConcurrentHashMap<>();
或地圖例如
public static Map<String, Integer> ageMap = new HashMap<>();
任何其他形式,簡化了get和put操作。
不需要編寫代碼,如
Object o = ageMap.get("Nick");
if(o instanceof Integer) {
Integer age = (Integer) o;
}
你可以簡單地寫
Integer age = ageMap.get("Nick");
「*使用一個字符串指定特定的HashMap中。*」 這是語無倫次。你究竟在做什麼? – dimo414
s是您的案例中的字符串。我想你的意思是age.get(「Nick」)而不是s.get(「Nick」) –