Grokking Java Interview Questions
0% completed
Generic Methods and Type Inference
The two assignments to a List<Number> below receive the result of the same call. The first one compiles, and the second one does not.
List<Number> a = List.of(120, 45); // compiles var prices = List.of(120, 45); List<Number> b = prices; // List<Integer> cannot be converted to List<Number>
In the first line, the compiler chose Number as the element type, because it could see where the result goes. In the second part, the list was already a List<Integer> when it reached b. The choice of a type without help from the programmer is called type inference.
.....
.....
.....
Like the course? Get enrolled and start learning!
Reading Progress
0%