【Java】JDK17新特性
JEP 356:增强型伪随机数生成器
地址:356
JDK 17 之前,我们可以借助 Random、ThreadLocalRandom 和SplittableRandom 来生成随机数。不过,这 3 个类都各有缺陷,且缺少常见的伪随机算法支持。
jdk17中为伪随机数生成器 (PRNG) 提供新的接口类型和实现,包括可跳转 PRNG 和另一类可拆分 PRNG 算法 (LXM)。
提供了一个新的接口RandomGenerator,它为所有现有和新的 PRNG 提供了统一的 API。RandomGenerators 提供了名为 ints、longs、doubles、nextBoolean、nextInt、nextLong 的方法。 nextDouble 和 nextFloat 及其所有当前参数变体。
示例
public static void main(String[] args) {
// 获取一个类型为 Xoshiro256PlusPlus(Xoroshiro128PlusPlus) 的随机数生成器工厂
RandomGeneratorFactory<RandomGenerator> factory = RandomGeneratorFactory.of("Xoshiro256PlusPlus");
// 使用工厂创建一个随机数生成器
RandomGenerator randomGenerator = factory.create();
// 生成 10 个随机数
randomGenerator.ints().limit(10)
.forEach(System.out::println);
}
JEP 406:switch 的模式匹配(预览版)
地址:406
通过 switch 的模式匹配增强 Java 编程语言 表达式和语句,以及对模式语言的扩展。 将模式匹配扩展到 switch 允许针对多个模式测试表达式,每个模式都有一个特定的作,以便可以简洁安全地表示面向数据的复杂查询。
正如 instanceof 一样, switch 也紧跟着增加了类型匹配自动转换功能。
instanceof 代码示例:
public static void main(String[] args) {
Object object = "jldsfjld";
//旧
if (object instanceof String) {
String s = (String)object;
System.out.println(s);
}
//新
if (object instanceof String s) {
System.out.println(s);
}
}
switch 代码示例
//旧
public NodeStrategy getJsonStrategy(SvgElementTypeEnum typeEnum) {
switch (typeEnum) {
case BackGround:
case group:
case Text:
return drawingBoardStrategy;
case Image:
return imageStrategy;
case SvgImage:
return iconStrategy;
default:
return imageStrategy;
}
}
//新
public NodeStrategy getJsonStrategy(SvgElementTypeEnum typeEnum) {
return switch (typeEnum) {
case BackGround, group, Text -> drawingBoardStrategy;
case Image -> imageStrategy;
case SvgImage -> iconStrategy;
default -> imageStrategy;
};
}