Diamond with anonymous classes
Code Comparison
Map<String, List<String>> map =
new HashMap<String, List<String>>();
// anonymous class: no diamond
Predicate<String> p =
new Predicate<String>() {
public boolean test(String s) {..}
};
Map<String, List<String>> map =
new HashMap<>();
// Java 9: diamond with anonymous classes
Predicate<String> p =
new Predicate<>() {
public boolean test(String s) {..}
};
Why the modern way wins
๐
Consistent rules
Diamond works everywhere โ constructors and anonymous classes alike.
๐งน
Less redundancy
Type arguments are stated once on the left, never repeated.
๐ง
DRY principle
The compiler already knows the type โ why write it twice?
Old Approach
Repeat Type Args
Modern Approach
Diamond <>
JDK Support
Diamond with anonymous classes
Available
Diamond with anonymous classes since JDK 9 (Sept 2017).
How it works
Java 7 introduced <> but it didn't work with anonymous inner classes. Java 9 fixed this, so you never need to repeat type arguments on the right-hand side.
Related Documentation
Proof