Using the diamond operator

Introduced in Java 9, the diamond operator can be used with anonymous classes if the inferred data type is denotable. When a data type is inferred, it suggests that the Java compiler can determine the data types in a method's invocation. This includes the declaration and any arguments contained within.

The diamond operator is the less than and greater than symbol pair ( <>). It is not new to Java 9; rather, the specific use with anonymous classes is.

The diamond operator was introduced in Java 7 and made instantiating generic classes simpler. Here is a pre-Java 7 example:

ArrayList<Student> roster = new ArrayList<Student>();

Then, in Java 7, we could rewrite it:

ArrayList<Student> roster = new ArrayList<>();

The problem was that this method could not be used for anonymous classes. Here is an example in Java 8 that works fine:

public interface Example<T> {
void aMethod() {
// interface code goes here
}
}

Example example = new Example<Integer>()
{

  @Override
public void aMethod() {
// code
}
};

While the preceding code works fine, when we change it to use the diamond operator, as shown here, a compiler error will occur:

public interface Example<T> {
void aMethod() {
// interface code goes here
}
}

Example example = new Example<>()
{
@Override
public void aMethod() {
// code
}
};

The error results from using the diamond operator with anonymous inner classes. Java 9 to the rescue! While the preceding code results in a compile-time error in Java 8, it works fine in Java 9, 10, and 11.