Java8新特性之构造器引用

一、构造器引用

和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。

二、数组引用

大家可以把数组看做是一个特殊的类,则写法和构造器引用一致

下面来看实例:

/*
 * @author zhCoding
 * @create 2020-08-10 15:32
 */
public class ConstructorReference {
    //构造器引用
    //Supplier中的T get()
    //Employee中的'new' Employee()
    @Test
    public void test1(){

        Supplier<Employee> sup1 = () -> new Employee();

        System.out.println("******************");

        Supplier<Employee> sup2 = Employee::new;

    }
    //BiFunction中的 R apply(T t,U u)
    @Test
    public void test2(){

        BiFunction<String,Integer,Employee> fun1 = (s,i) -> new Employee(s,i);
        System.out.println(fun1.apply("Tom", 18));

        System.out.println("**********************");

        BiFunction<String,Integer,Employee> fun2 = Employee::new;
        System.out.println(fun2.apply("Jerry", 17));
    }

    //数组引用
    //Function中的R apply(T t)
    @Test
    public void test3(){
        int[] arr = new int[]{1,2,3,4,5,6};

        Function<Integer,Integer> fun1 = n -> arr[n];
        System.out.println(fun1.apply(2));

        System.out.println("****************");

        Function<Integer,String[]> fun2 = length -> new String[length];
        System.out.println(Arrays.toString(fun2.apply(5)));

        System.out.println("*****************");

        Function<Integer,String[]> fun3 = String[]::new;
        System.out.println(Arrays.toString(fun3.apply(10)));
    }
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值