Java 12
Java 12
Switch 表达式(JEP 325)
在
// 通过传入月份,输出月份所属的季节
public static void switchJava12Before(String day) {
switch (day) {
case "march":
case "april":
case "may":
System.out.println("春天");
break;
case "june":
case "july":
case "august":
System.out.println("夏天");
break;
case "september":
case "october":
case "november":
System.out.println("秋天");
break;
case "december":
case "january":
case "february":
System.out.println("冬天");
break;
}
}
上面的例子中,通过传入一个月份,输出这个月份对应的季节。简单的功能却写了大量代码,而且每个操作都需要一个
# 编译时
./bin/javac --enable-preview -source 12 ./Xxx.java
# 运行时
./bin/java --enable-preview Xxx
由于
public static void switchJava12(String day) {
switch (day) {
case "march", "april", "may" -> System.out.println("春天");
case "june", "july", "august" -> System.out.println("夏天");
case "september", "october", "november" -> System.out.println("秋天");
case "december", "january", "february" -> System.out.println("冬天");
}
}
通过测试可以得到预期的输出结果。这还不够,在
String season = switch (day) {
case "march", "april", "may" -> "春天";
case "june", "july", "august" -> "春天";
case "september", "october", "november" -> "春天";
case "december", "january", "february" -> "春天";
default -> {
//throw new RuntimeException("day error")
System.out.println("day error");
break "day error";
}
};
System.out.println("当前季节是:" + season);
虽然编写更加简单了,其实这些只不过是语法糖式的更新,编译后和之前并没有太大区别。
文件对比Files.mismatch
在
// 创建两个文件
Path pathA = Files.createFile(Paths.get("a.txt"));
Path pathB = Files.createFile(Paths.get("b.txt"));
// 写入相同内容
Files.write(pathA,"abc".getBytes(), StandardOpenOption.WRITE);
Files.write(pathB,"abc".getBytes(), StandardOpenOption.WRITE);
long mismatch = Files.mismatch(pathA, pathB);
System.out.println(mismatch);
// 追加不同内容
Files.write(pathA,"123".getBytes(), StandardOpenOption.APPEND);
Files.write(pathB,"321".getBytes(), StandardOpenOption.APPEND);
mismatch = Files.mismatch(pathA, pathB);
System.out.println(mismatch);
// 删除创建的文件
pathA.toFile().deleteOnExit();
pathB.toFile().deleteOnExit();
// RESULT
// -1
// 3
Compact Number
简化的数字格式可以直接转换数字显示格式,比如
System.out.println("Compact Formatting is:");
NumberFormat upvotes = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), Style.SHORT);
System.out.println(upvotes.format(100));
System.out.println(upvotes.format(1000));
System.out.println(upvotes.format(10000));
System.out.println(upvotes.format(100000));
System.out.println(upvotes.format(1000000));
// 设置小数位数
upvotes.setMaximumFractionDigits(1);
System.out.println(upvotes.format(1234));
System.out.println(upvotes.format(123456));
System.out.println(upvotes.format(12345678));
可以得到输出如下:
100
1K
10K
100K
1M
1.2K
123.5K
12.3M
JVM 相关更新
Shenandoah 垃圾收集器
更多关于
ZGC 并发类卸载
JVM 常量API
在包
默认使用类数据共享(CDS)
这已经不是