0
点赞
收藏
分享

微信扫一扫

java9新特性

斗米 2022-03-22 阅读 190


jdk9新增测试⼯具jshell

jdk9新增的接⼝私有⽅法

  • 什么是jdk9新增的接⼝私有⽅法
  • JDK8新增了静态⽅法和默认⽅法,但是不⽀持私有⽅法
  • jdk9中新增了私有⽅法
public interface OrderPay {
void pay();
default void defaultPay(){
privateMethod();
}
//接⼝的私有⽅法可以在JDK9中使⽤
private void privateMethod(){
System.out.println("调⽤接⼝的私有⽅法");
}
}
public class OrderPayImpl implements OrderPay {
@Override
public void pay() {
System.out.println("我实现了接⼝");
}
}
public static void main(String[] args) throws Exception {
OrderPay orderPay = new OrderPayImpl();
orderPay.defaultPay();
orderPay.pay();
}
  • 注意点:
  • 接⼝中的静态⽅法不能被实现类继承和⼦接⼝继承,但是接⼝中的⾮静态的默认⽅法可以被实现类继承
  • 例如List.of() ⽅法,ArrayList虽然继承了List,但是不能⽤ArrayList.of()⽅法
    类的静态⽅法可以被继承

JDK9新特性之增强try-with-resource

  • 什么是try-with-resource
    在JDK7中,新增了try-with-resources语句,可以在try后的括号中初始化资源,可以实现资源⾃动关闭

  • 什么是增强try-with-resource
    在JDK9中,改进了try-with-resources语句,在try外进⾏初始化,在括号内引⽤,即可实现资源⾃动关闭,多个变量则⽤分号进⾏分割
    不需要声明资源 out 就可以使⽤它,并得到相同的结果

public static void main(String[] args) throws Exception {
String path = "/Users/xdclass/Desktop/t.txt";
test(path);
}
private static void test(String filepath) throws FileNotFoundException {
OutputStream out = new FileOutputStream(filepath);
try (out) {
out.write((filepath + "可以学习java架构课程").getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}

jdk9⾥⾯新增的集合容器API,快速创建只读集合

  • 什么是只读集合
    集合只能读取,不能增加或者删除⾥⾯的元素
  • JDK9之前创建只读集合
List<String> list = new ArrayList<>();
list.add("SpringBoot课程");
list.add("架构课程");
list.add("微服务SpringCloud课程");
//设置为只读List集合
list = Collections.unmodifiableList(list);
System.out.println(list);
Set<String> set = new HashSet<>();
set.add("Mysql教程");
set.add("Linux服务器教程");
set.add("Git教程");
//设置为只读Set集合
set = Collections.unmodifiableSet(set);
System.out.println(set);
Map<String, String> map = new HashMap<>();
map.put("key1", "课程1");
map.put("key2", "课程2");
//设置为只读Map集合
map = Collections.unmodifiableMap(map);
System.out.println(map);
  • JDK9后创建只读集合
List<String> list = List.of("SpringBoot课程", "架构课程", "微服务SpringCloud课
");
System.out.println(list);
Set<String> set = Set.of("Mysql教程", "Linux服务器教程", "Git教程");
System.out.println(set);
Map<String, String> map = Map.of("key1", "课程1", "key2", "课程2");
System.out.println(map);

java9之新增Stream API

  • JDK8⾥⾯新增的Stream流式编程,⽅便了很多数据的处理
  • jdk9⾥⾯新增了部分API
  • takeWhile
    有序的集合:从 Stream 中获取⼀部分数据, 返回从头开始的尽可能多的元素, 直到遇到第⼀个false结果,如果第⼀个值不满⾜断⾔条件,将返回⼀个空的 Stream
List<String> list =
List.of("springboot","java","html","","git").stream().takeWhile(obj-
>!obj.isEmpty()).collect(Collectors.toList());
//⽆序集合,返回元素不固定,暂⽆⽆实际使⽤场景
Set<String> set =
Set.of("springboot","java","html","","git").stream().takeWhile(obj-
>!obj.isEmpty()).collect(Collectors.toList());
  • dropWhile
    与 takeWhile相反,返回剩余的元素,和takeWhile⽅法形成互补
List<String> list =
List.of("springboot","java","html","","git").stream().dropWhile(obj -> !obj.isEmpty()).collect(Collectors.toList());



举报

相关推荐

0 条评论