将hash1 声明为HashMap<String, ?> 表示变量hash1 可以包含任何HashMap,其键为String 和任何类型的值。
HashMap<String, ?> map;
map = new HashMap<String, Integer>();
map = new HashMap<String, Object>();
map = new HashMap<String, String>();
以上所有内容都是有效的,因为变量 map 可以存储任何这些哈希映射。该变量不关心它所持有的哈希映射的 Value 类型是什么。
使用通配符不,但是,您可以将任何类型的对象放入地图中。事实上,使用上面的哈希映射,您不能使用map 变量将任何内容放入其中:
map.put("A", new Integer(0));
map.put("B", new Object());
map.put("C", "Some String");
上面所有的方法调用都会导致编译时错误,因为Java不知道map里面的HashMap的Value类型是什么。
您仍然可以从哈希映射中获取值。尽管您“不知道值的类型”(因为您不知道变量中的哈希映射的类型),但您可以说一切都是Object 的子类,因此,无论您得到什么地图的类型将是 Object:
HashMap<String, Integer> myMap = new HashMap<>();// This variable is used to put things into the map.
myMap.put("ABC", 10);
HashMap<String, ?> map = myMap;
Object output = map.get("ABC");// Valid code; Object is the superclass of everything, (including whatever is stored our hash map).
System.out.println(output);
上面的代码块将打印 10 到控制台。
所以,最后,当您不关心(即无关紧要)HashMap 的类型是什么时,请使用带有通配符的 HashMap,例如:
public static void printHashMapSize(Map<?, ?> anyMap) {
// This code doesn't care what type of HashMap is inside anyMap.
System.out.println(anyMap.size());
}
否则,请指定您需要的类型:
public void printAThroughZ(Map<Character, ?> anyCharacterMap) {
for (int i = 'A'; i <= 'Z'; i++)
System.out.println(anyCharacterMap.get((char) i));
}
在上述方法中,我们需要知道 Map 的键是 Character,否则,我们将不知道使用什么类型从中获取值。但是,所有对象都有一个toString() 方法,因此映射可以具有任何类型的对象作为其值。我们仍然可以打印这些值。