正常实例化和实例化之间的区别,包括方法引用

Dav*_*idO 4 java java-8 java-stream method-reference

为什么在第一种情况 SomeClass 只实例化一次,但在第二种情况下 n 次,其中 n 是流中的元素数?

List<SomeClass> list = stream.map(new SomeClass()::method)
                            .collect(Collectors.toList());

Run Code Online (Sandbox Code Playgroud)
List<SomeClass> list = stream.map(a -> {return new SomeClass().method(a);})
                            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

在这种情况下,方法“method”返回对象本身(= return this)。

所以在第一种情况下,列表只包含一个对象,但包含 n 次。在第二种情况下,列表包含 n 个不同的对象。

重现问题:主要:

Arrays.asList(true, false, true, false).stream().map(new SomeClass()::method)
                                                .collect(Collectors.toList());

System.out.println("----------------------");
        
Arrays.asList(true, false, true, false).stream().map(a -> {return new SomeClass().method(a);})
                .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

和 SomeClass.java:

public class SomeClass {
    
    public SomeClass() {
        System.out.println(this);
    }
    
    public SomeClass method(Boolean b) {
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 6

Method references only comes in four kinds (See "Kinds of method references" in this page):

  • References to a static method
  • References to an instance method of a particular object
  • Reference to an instance method of an arbitrary object of a particular type
  • Reference to a constructor

没有一种“每次都创建一个新对象”的方法引用,无论这意味着什么。new SomeClass()::methodName属于第二种。它指的methodName一个特定对象的方法。该对象是新创建的SomeClass对象。它不会产生任何更多SomeClass的时候调用该方法的对象,因为这是一个参考someMethod特定 SomeClass你新创建的对象。

另一方面,lambda 表达式SomeClass每次被调用时都会创建一个新的,因为new SomeClass(){ ... }.