GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev โ Diamond with anonymous classes | java.evolved
Language
Beginner
Diamond with anonymous classesDiamond operator now works with anonymous classes too. Code Comparison
โ 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) {..}
};
See a problem with this code? Let us know.
Why the modern way wins
๐
Consistent rulesDiamond works everywhere โ constructors and anonymous classes alike. ๐งน
Less redundancyType arguments are stated once on the left, never repeated. ๐ง
DRY principleThe compiler already knows the type โ why write it twice? Old Approach
Repeat Type Args
Modern Approach
Diamond <>
Since JDK
9
Difficulty
Beginner
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
Related patterns
Language
Beginner
Type inference with varJava 8
Map<String, List<Integer>> map =
new HashMap<String, List<Integer>>();
for (Map.Entry<String, List<Integer>> e
: map.entrySet()) {
// verbose type noise
}
Java 10+
var map = new HashMap<String, List<Integer>>();
for (var entry : map.entrySet()) {
// clean and readable
}
JDK 10+
โ
Language
Beginner
Text blocks for multiline stringsJava 8
String json = "{\n" +
" \"name\": \"Duke\",\n" +
" \"age\": 30\n" +
"}";
Java 15+
String json = """
{
"name": "Duke",
"age": 30
}""";
JDK 15+
โ
Language
Beginner
Switch expressionsJava 8
String msg;
switch (day) {
case MONDAY:
msg = "Start";
break;
case FRIDAY:
msg = "End";
break;
default:
msg = "Mid";
}
Java 14+
String msg = switch (day) {
case MONDAY -> "Start";
case FRIDAY -> "End";
default -> "Mid";
};
JDK 14+
โ
|
| You are visitor 01402503 โ GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800ร600. No cookies required. |