Language Początkujący

Diamond operator now works with anonymous classes too.

✕ 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ć.
📏

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
Diamond with anonymous classes
Dostępne

Diamond with anonymous classes since JDK 9 (Sept 2017).

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.

Udostępnij 𝕏 🦋 in