我有这段代码,无法编译:
import java.util.ArrayList;
import java.util.List;
public class TypeSafetyTest {
public static void main(String[] args) {
TypeSafetyTest test = new TypeSafetyTest();
test.run();
}
private void run() {
Car car = new Car();
List<String> wheelWeights = car.getWheelWeights();
}
private class Car {
List<Double> wheelWeights = new ArrayList<Double>();
public List<Double> getWheelWeights() {
return wheelWeights;
}
public void setWheelWeights(List<Double> wheelWeights) {
this.wheelWeights = wheelWeights;
}
}
}
它在行上给出了“不兼容的类型”错误:
List<String> wheelWeights = car.getWheelWeights();
但是,如果我换行:
private class Car {
到
private class Car<T> {
然后代码成功编译,并在曾经出现编译错误的行上显示警告“未检查的分配”。为什么会这样?我期待它在这两种情况下都会出现编译错误。