在JDK 17中,switch语句引入了模式匹配(Pattern Matching)和增强的switch表达式,这是Java语言的重要改进。以下是JDK 17中switch的核心特性:
一、 模式匹配(Preview Feature)
JDK 17中,switch支持类型模式匹配,允许直接在case中匹配类型并提取变量。
(1)匹配多种类型
public class Test3 {
public static void main(String[] args) {
Object obj = "back";
switch (obj) {
case Integer i -> System.out.println("Integer");
case String s -> System.out.println("String");
default -> System.out.println("Other");
}
}
}
注意:模式匹配是预览特性,需通过
--enable-preview启用(编译和运

最低0.47元/天 解锁文章
1717

被折叠的 条评论
为什么被折叠?



