在Java Collections Map<Key,?> 中“?”是什么意思?参考?

In Java Collections Map<Key,?> What does "?" refer to?

在JavaCollections中我看到了这样的东西:Map<Key,?>。 我不知道它是如何工作的,任何人都可以帮我解决这个问题或提供一个例子吗?

问号 (?) 表示未知类型。

在您的示例中,Map<Key, ?>,这意味着它将匹配包含任何类型值的映射。 并不意味着您可以创建一个Map<Key, ?>并在其中插入任何类型的值。

引自documentation

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

例如,假设您要创建一个函数来打印任何地图的值,而不考虑值类型:

static void printMapValues(Map<String, ?> myMap) {
    for (Object value : myMap.values()) {
        System.out.print(value + " ");
    }
}

然后调用这个函数传递一个Map<String, Integer>作为参数:

Map<String, Integer> myIntMap = new HashMap<>();
myIntMap.put("a", 1);
myIntMap.put("b", 2);
printMapValues(myIntMap);

你会得到:

1 2

通配符允许您调用 相同的函数 传递 Map<String, String> 或任何其他值类型作为参数:

Map<String, String> myStrMap = new HashMap<>();
myStrMap.put("a", "one");
myStrMap.put("b", "two");
printMapValues(myStrMap);

结果:

one two

此通配符称为 unbounded,因为它不提供有关类型的信息。有几种情况您可能需要使用无界通配符:

  • 如果除了 Object class.
  • 中定义的方法外,您没有调用任何方法
  • 当您使用不依赖于类型参数的方法时,例如 Map.size()List.clear()

通配符可以是无界的、上限的或下限的:

  • List<?> 无限通配符 的一个例子。它表示未知类型的元素列表。

  • List<? extends Number> 上限通配符 的示例。它匹配 Number 类型的 List 及其子类型,例如 IntegerDouble.

  • List<? super Integer> 下界通配符 的一个例子。它匹配 Integer 类型的 List 及其超类型 NumberObject.

未知通配符

? 可以是任何数据类型

List<?> 表示类型为未知类型的列表,这可能是 List<Integer>List<Boolean>List<String>

现在来看你的例子Map<Key,?>意味着Value要插入到这个地图中的可以是任何数据类型。