Fork me on GitHub

Programming, Internet & more

Java 9 Diamond Operator and anonymous classes

This is another post about a new feature in Java 9. Today, I will show you that you can use the diamond operator along with anonymous classes.

Diamond Operator

We all know about the Diamond Operator since Java 7. It allows us to leave out the generic type on the right side of an expression. For example, let’s declare a simple list:

// before Java 7, explicit generic type declaration required
List<String> myList = new ArrayList<String>();

// since Java 7, diamond operator can be used
List<String> myList = new ArrayList<>();

Unfortunately, the use of the Diamond Operator was not possible for anonymous inner classes. The situation was not very consistent because the generic type of an anonymous inner class can be deduced just as from a normal class.

Since Java 9 the situation has improved and it is now possible to use the Diamond Operator also in anonymous inner classes. Let’s take a look at this example:

// possible since Java 9, diamond operator can be used
Predicate<Integer> predicate = new Predicate<>() {
    public boolean test(Integer input) {
        return input == 42;


With the introduction of lambda expressions in Java 8, anonymous inner classes have become less important. However, sometimes they are still useful and even can improve readability. Therefore, it is very good that the inconsistency with the Diamond Operator has been removed and it is now possible to use it also on anonymous inner classes.

Category: java9

Leave a Reply

Your email address will not be published. Required fields are marked *