Method reference does not compile
Why does this not compile?
Stream.generate(Integer::new(1)).limit(10);
It gives the error
Syntax error on token "new", AssignmentOperator expected after this token
Sure, I could rewrite this expression to
Stream.generate(() -> new Integer(1)).limit(10);
but I want to know the reason why the first statement is failing...
You can't pass arguments to method references explicitly. They can only be passed implicitly.
For example, if you have an IntStream
, you can mapToObj
it to Integer
instances using a method reference of the public Integer(int value)
constructor :
IntStream.of(1,1,1).mapToObj(Integer::new)...
Of course, using the public Integer(int value)
constructor for small int
values is usually a bad idea, since it may result in the creation of unnecessary multiple instances all having the same int
value, instead of taking advantage of the IntegerCache
, which caches Integer
instances of small values (-128 to 127).
上一篇: JavaScript正则表达式来查找未包裹在标签中的特殊字词
下一篇: 方法引用不编译