Diamond with anonymous classes
Diamond operator now works with anonymous classes too.
Porównanie kodu
✕ Java 7/8
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) {..}
};
✓ Java 9+
Map<String, List<String>> map =
new HashMap<>();
// Java 9: diamond with anonymous classes
Predicate<String> p =
new Predicate<>() {
public boolean test(String s) {..}
};
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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?
Stare podejście
Repeat Type Args
Nowoczesne podejście
Diamond <>
Od JDK
9
Poziom trudności
Początkujący
Wsparcie JDK
Diamond with anonymous classes
Dostępne
Diamond with anonymous classes since JDK 9 (Sept 2017).
Jak to działa
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.
Powiązana dokumentacja