Java Reference
In-Depth Information
import java.util.Arrays;
import java.util.List;
// Other code goes here
List<String> list1 = Arrays.asList("A", "B");
List<Integer> list2 = Arrays.asList(9, 19, 1969);
Consider the following statement that uses the diamond operator:
List<String> list3 = new ArrayList<>(list1); // Inferred type is String
The compiler used the constructor argument
list1
to infer the type. The static type of
list1
is
List<String>
,
so the type
String
was inferred by the compiler. The above statement compiles fine. The compiler did not use the
left-hand side of the assignment operator,
List<String> list3
, during the inference process. You may not trust this
argument. Consider the following statement to prove this:
List<String> list4 = new ArrayList<>(list2); // A compile-time error
Compiling the above statement generates the following error:
required: List<String>
found: ArrayList<Integer>
1 error
Do you believe it now? The constructor argument is
list2
whose static type is
List<Integer>
. The compiler
inferred the type as
Integer
and replaced
ArrayList<>
by
ArrayList<Integer>
. The type of
list4
is
List<String>
,
which is not assignment-compatible with the
ArrayList<Integer>
, which resulted in the compile-time error.
Consider the following statement:
List<String> list5 = new ArrayList<>(); // Inferred type is String
This time, there is no constructor argument. The compiler uses the second step to look at the left-hand side of the
assignment operator to infer the type. On the left-hand side, it finds
List<String>
and it correctly infers the type as
String
. Consider a
process()
method that is declared as follows:
public static void process(List<String> list) {
// Code goes here
}
The following statement makes a call to the
process()
method, which might generate a compile-time error:
// The inferred type is Object in Java 7, and String in Java 8 and later
process(new ArrayList<>());
The above statement generates the following compile-time error in Java 7. It will compile fine in Java 8 as Java
designers have been trying to make the compiler smarter a little bit at time!
required: List<String>
found: ArrayList<Object>
1 error