Monday, June 13, 2011

JDK7: The Diamond Operator in Java SE 7

Starting in Java SE 7, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond operator.

For example, you can create an instance ofBox<Integer> with the following statement:

Box<Integer> integerBox = new Box<>();

For more information about the diamond operator, see Type Inference and Instantiation of Generic Classes.
Note that using the diamond operator to infer the actual type parameters of the generic class being instantiated is different than inferring the actual type parameters of generic constructors (which is similar to generic methods and does not require the diamond operator).

See Type Inference and Generic Constructors of Generic and Non-Generic Classes for more information.

No comments :

Post a Comment