I saw code like this today:
public class GenClass<T> { ... }
//in some other class
GenClass g = new GenClass<>();
Does the <>
accomplish anything at all here? Normally <>
would tell the compiler to determine the generic parameter(s) based on context, but in this case there's no context. But apparently it's legal. Is there any difference between this and the following?
GenClass g = new GenClass();
Diamond Operator: Diamond operator was introduced in Java 7 as a new feature. The main purpose of the diamond operator is to simplify the use of generics when creating an object. It avoids unchecked warnings in a program and makes the program more readable.
The diamond operator – introduced in Java 1.7 – adds type inference and reduces the verbosity in the assignments – when using generics: List<String> cars = new ArrayList<>(); The Java 1.7 compiler's type inference feature determines the most suitable constructor declaration that matches the invocation.
It's called diamond operator and infers the generic type from the left hand side, if possible.
The diamond is doing what it always does - inferring the generic type from the context, and providing assurance that the constructor call does not compromise type-safety.
Consider this example:
public class GenClass<T> {
GenClass(T t, List<T> list) {}
public static void main(String[] args) {
GenClass m = new GenClass<>(1, new ArrayList<String>()); // Doesn't compile
}
}
This example does not compile, because an appropriate type could not be inferred. If you remove the diamond it does compile because the types of the constructor arguments are the erased versions (Object
and List
).
In your case, the constructor takes no arguments, so there is nothing really to check. However, using a diamond is a good habit to get into, even when you choose to assign the result of a constructor invocation to Object
or a raw type (not that you should use raw types).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With