jdk新特性
本内容学习自知秋老师的翻译课程
jdk10引入的类型推断
代码示例:
package com.wxit.api;
import java.util.List;
/**
* @author wj
* @date 2021.10.18 14:42
* jdk10引入的类型推断
*/
public class TypeInterfaceDemo {
public static void main(String[] args) {
var name1 = List.of("吴杰","佳伟");
List<String> name2 = List.of("婷姐","子龙");
//在这里可以看到左侧的类型声明变得很复杂
// List<List<String>> names = List.of(name1,name2);
//你也可以创建final变量,如果你不希望任何人能够修改它,默认情况下不是final的
final var names = List.of(name1,name2);
names.stream().forEach(System.out::println);
for (var name : name1) {
System.out.println(name);
}
//仅当右侧存在某种对象的时候,Java才能推断出类型,var不是一个关键字
// var abc = null;
}
}
jdk14引入的switch表达式
代码示例:
package com.wxit.api;
/**
* @author wj
* @date 2021.10.18 14:55
* jdk14引入的switch表达式
*/
public class SwitchExpressionDemo {
public static void main(String[] args) {
}
public static String findDayOfTheWeek(int day){
String dayOfWeek = "";
switch (day){
case 0: dayOfWeek = "星期一";break;
case 1: dayOfWeek = "星期二";break;
case 2: dayOfWeek = "星期三";break;
case 3: dayOfWeek = "星期四";break;
default: throw new IllegalArgumentException("-----" + day);
}
return dayOfWeek;
}
public static String findDayOfTheWeek2(int day){
String dayOfWeek = switch (day) {
case 0 -> {
System.out.println("-----");
yield "星期一";
}
case 1 -> "星期二";
case 2 -> "星期三";
case 3 -> "星期四";
default -> throw new IllegalArgumentException("-----" + day);
};
return dayOfWeek;
}
}