gpt4 book ai didi

java - 类型推断算法的什么变化导致了这种行为?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:54:23 26 4
gpt4 key购买 nike

我正在阅读 OCP Java SE7, certification guide from Mala Gupta .在第297页,以下代码片段

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

public class TestGenericTypeInference {
Map<String,Double> salaryMap = new HashMap<>();
Map<String,Object> copySalaryMap = new HashMap<>(salaryMap);
}

正在使用 java 8 进行编译,但使用 java 7 时编译器会报错:

TestGenericTypeInference.java:8: error: incompatible types: HashMap<String,Double> cannot be converted to Map<String,Object>
Map<String,Object> copySalaryMap = new HashMap<>(salaryMap);
^

我的问题是:类型推断算法的什么变化导致了这种行为?

最佳答案

我的问题的答案:

What change in type inference algorithm causes this behavior?

the Generics FAQ from Angelina Langer .给出一个类似的例子:

// error in Java 7 ; fine since Java 8 
Set<Number> s3 = new HashSet<>(Arrays.asList(0L,0L));
  • The [...] expression demonstrates that the lefthand side of the assignment is indeed ignored (in Java 7). The compiler again infers from the constructors argument, i.e., the result of the asList method, that the missing type parameter for the new HashSet must be Long . This leads to a type mismatch and an according error message. The compiler does not conclude that the missing type parameter should be Number because it ignores the lefthand side of the assignment. In Java 8, the type inference was modified and improved. Since then, compiler infers Number as the type parameter form the new HashSet on the right-hand side of the compiler and from that deduces Number as the type parameter for the asList method. In Java 8, this compiles just fine.

关于java - 类型推断算法的什么变化导致了这种行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34875406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com