构造器引用(和方法引用一样,构造器本质上也是一个方法 <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());

 

 

posted @ 2021-07-24 23:42  Vermeer  阅读(91)  评论(0)    收藏  举报