As long as the compiler can infer a type parameter from the context, you can use an empty set of type parameters (<>. This pair of angle brackets is usually calledDiamond.
For example, consider the following Variable declaration:
Map
> myMap = new HashMap
>();
In Java SE 7, you can use an empty set of type parameters (<>) To replace the parameterized type of the constructor:
Map
> myMap = new HashMap<>();
Note: To use automatic type inference during generic class initialization, you must specify diamond. In the following exampleHashMap()The constructor referencesHashMapOriginal Type insteadMap > Type. The Compiler generates an unchecked conversion warning:
Map
> myMap = new HashMap(); // unchecked conversion warning
Java SE 7 has limited support for type inference for instance creation. In terms of context, type inference can be used only when the parameterized type of the constructor is obvious. For example, the following example fails to be compiled:
List
list = new ArrayList<>();list.add("A"); // The following statement should fail since addAll expects // Collection
list.addAll(new ArrayList<>());
Note: diamond usually plays a role in method calls. However, we recommend that you use diamond first when declaring variables.
In contrast, the following example can be compiled through:
// The following statements compile:List
list2 = new ArrayList<>();list.addAll(list2);
Type inference and constructors of generic and non-generic classes
Note: In generic and non-generic classes, constructors can all be generic (in other words, declare their own form parameters ):
class MyClass
{
MyClass(T t) { // ... }}
Consider the followingMyClassClass initialization is valid in Java SE 7 and earlier versions:
new MyClass
("")
This statement creates a parameterized typeMyClass Is an instance; it is explicitly a generic classMyClass SpecifyIntegerType as form parameterX. Note that the constructor of this generic class contains a form parameter. The compiler inferred that the form parameter T type of the constructor of this generic class isString(Because the actual parameter of this constructor isStringObject ).
Before Java SE 7, the compiler can infer the actual parameters of the generic constructor, just like the generic method. However, in Java SE 7, if you use diamond (<>), The compiler can infer the actual parameters of the instantiated generic class. The following example is valid in Java SE 7 and later versions:
MyClass
myObject = new MyClass<>("");
In this example, the compiler infers generic classes.MyClass Format parametersXIsInteger. It is inferred that the type of the form parameter T of the constructor of this generic class isString.
This article is translated from the Oracle official documentation workshop!