使用Java 8流时的新对象实例化 [英] New object instantiation when using Java 8 streams
问题描述
使用以下构造除了在后者中的可读性稍好以外,是否还有其他区别?
Is there a differnce in using the following contstructs, other than slightly better readability in the latter?
someList.stream().map(item -> new NewClass(item)).collect(Collectors.toList());
someList.stream().map(NewClass::new).collect(Collectors.toList());
推荐答案
通常没有区别. NewClass::new
生成的字节码更少,因为在lambda版本中,java编译器从lambda主体创建了自动生成的私有方法,而NewClass:new
直接链接到构造函数方法句柄.因此,使用方法引用时,类文件的大小可能会略少一些.不过,预计不会有明显的性能差异.
Generally there's no difference. NewClass::new
produces less bytecode as in lambda version an auto-generated private method is created by java compiler from the lambda body while NewClass:new
directly links to the constructor method handle. So using method references you may have slightly less class file size. No significant performance difference is expected though.
另一个区别是方法解析过程.它不适用于您的特定示例,但可能适用于其他代码.例如,您有两个构造函数:
Another difference is method resolution procedure. It's not applicable in your particular example, but may be applicable in other code. For example, you have two constructors:
public NewClass(String a) {...}
public NewClass(String a, String b) {...}
并且您有一些接受功能接口的方法:
And you have some method which accepts functional interface:
public myMethod(Function<String, NewClass> fn) {...}
然后您可以使用lambda或功能接口来调用它:
Then you can call it both with lambda or functional interface:
myMethod(str -> new NewClass(str));
myMethod(NewClass::new);
但是假设以后您添加一个新的名称相同的方法:
But suppose that later you add a new method with the same name like this:
public myMethod(BiFunction<String, String, NewClass> fn) {...}
然后,方法引用调用将变得模棱两可,并且会导致编译错误,因为NewClass::new
现在可以同时匹配两个构造函数,而lambda仍是模棱两可的.
Then method reference call will become ambiguous and will result in compilation error as NewClass::new
now matches to both constructors, while lambda is still unambiguous.
这篇关于使用Java 8流时的新对象实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!