构造器引用(和方法引用一样,构造器本质上也是一个方法 <init> 方法)
2016年的 OneNote 笔记迁移到 博客园
构造方法引用和其他方法引用是一样的,和方法引用中 类 ::实例方法 一样

@Test public void test1() { Function<Integer, Person> f1 = new Function<Integer, Person>() { @Override public Person apply(Integer t) { return new Person(t); } };
// ----------------------------lambda表达式------------------------------ Function<Integer, Person> f2 = t -> new Person(t); // -----------------------------构造器的引用----------------------------- Function<Integer, Person> f3 = Person::new; }
解释:
Apply()方法中第一个泛型是形参类型,第二个泛型是返回值返回值类型,所以构造器引用时,将返回类型的对象new,将第一个参数作为形参

/** * 数组引用 */ @Test public void test2() { Function<Integer, Person[]> f1 = new Function<Integer, Person[]>() { @Override public Person[] apply(Integer t) { return new Person[t]; } };
// ---------------------------------lambda表达式------------------------------ Function<Integer, Person[]> f2 = t -> new Person[t];
// ---------------------------------数组的引用------------------------------ Function<Integer, Person[]> f3 = Person[]::new; // 调用 Person[] apply = f3.apply(10); }
解释:
Apply()方法中第一个泛型是形参类型,第二个泛型是返回值返回值的数组类型,所以构造器引用时,将返回类型的对象new,将第一个参数作为返回数组的长度
使用案例:
List<String> newStrList = Arrays.asList(1,2,3,4,5).stream().map(String::new).collect(Collectors.toList());
本文来自博客园,作者:Vermeer,转载请注明原文链接:https://www.cnblogs.com/chxlay/p/15056753.html

浙公网安备 33010602011771号