java - Java 是否根据结果假定类型?

Java中有一段代码:

import java.util.HashMap;
import java.util.Collection;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<Integer, String> langMap = new HashMap<>();
    langMap.put(1, "Java");
    langMap.put(2, "C#");
    Collection<String> values = langMap.values();
  }
}

在最后一行代码中有 Collection<String> .不是 <String>不必要,因为类型是根据 langMap 分配的值假定的?

最佳答案

Isn't <String> unnecessary

不,这是必要的:没有<String> ,变量的类型将是 Collection ,这是一个原始类型。 Don't use raw types .

我想 Java 可以为类似 Collection<> 这样的上下文提供一个符号,类似于 diamond notation ,但事实并非如此。

你要么必须使用 Collection<String> , 或 var支持它的语言版本(11 及更高版本)。

https://stackoverflow.com/questions/65873194/

相关文章:

reactjs - 有没有 Ionicons : Icon props?

javascript - 句号、单词和冒号的正则表达式

c# - 如何使 IEnumerable 和 IQueryable 异步?

python - 如何连接来自 3 个小整数的字节以生成由 Python 中的这些字节表示的更大数字

javascript - 对象可能是 'null' : TypeScript, React useR

list - 在 Elixir 中使用类型规范中的原子列表

react-native - react native : Refresh Controll not

haskell - 为什么 map 使用的这个函数需要返回一个(单例)列表而不是一个元素?

vuejs3 - vue3 中 shallowReactive 和 shallowRef 的区别?

python - 如何从时间序列数据中选择前 n 列而不是在 pandas 中使用 nlargest