1. Introduction
From Java 9, Diamond operator can be used for anonymous classes. Until Java 8, you could not apply diamond operator for anonymous generic classes.
To understand what this statement means, we’ll first discuss the usage of diamond operator before Java 9. And then the enhancement in Java 9.
2. Java 7 diamond operator (<>)
Diamond Operator ‘<>’ was introduced in JDK 7. The type arguments required to invoke the constructor of a generic class can be replaced with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets (<>) is informally called the diamond.
Prior to Java 7, it was mandatory to explicitly include the type of generic class in the type parameter of the constructor.
ArrayList<String> l = new ArrayList<String>();
From Java 7, you can write the above statement like this:
ArrayList<String> l = new ArrayList<>();
Until Java 8, you can not apply diamond operator for anonymous generic classes. This was improved in Java 9.
3. Diamond operator for anonymous classes
In JDK 9, usage of diamond operator extended to anonymous classes.
The class declared without having the name are called anonymous class.
ArrayList<String> l = new ArrayList<String>(){
};
Here, a child class is created which extends ArrayList
class without name (and thus an anonymous class) and we are creating object for that child class.
From JDK 9 onwards you can use diamond operator for anonymous classes also.
ArrayList<String> l = new ArrayList<>(){
};
This is a valid syntax in Java 9.
4. Conclusion
In this short article, we discussed Java 9 diamond operator enhancement with example. This is a very small but important enhancement.
Hope this article was helpful.