I have this code, which fails to compile:
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;
}
}
}
It gives an "Incompatible types" error on the line:
List<String> wheelWeights = car.getWheelWeights();
However, if I change the line:
private class Car {
to
private class Car<T> {
then the code compiles successfully with the warning "Unchecked assignment" on the line that used to have the compile error. Why is this so? I was expecting it to give a compile error in both cases.