Method reference with a full constructor call as a lambda expression in Java

会有一股神秘感。 提交于 2019-12-01 05:18:03

Well new AtomicInteger(1) returns an instance, so it's the second one. The exact details of how this is translated are implementation specific, but it's a single instance created and this is back-ed up by the JLS 15.13.3

First, if the method reference expression begins with an ExpressionName or a Primary, this subexpression is evaluated

In plain english, the part before :: is evaluated when it's declaration is first encountered.

Your assumption how this is translated is almost correct, it's like generating an instance outside of the function itself and using that - since it is effectively final, this is permitted.

It's simply the second type: a reference to a method of a specific object, there's no additional logic behind the curtain.

You can replace

Stream.generate(new AtomicInteger(1)::getAndIncrement)...

with

AtomicInteger containingObject = new AtomicInteger(1);
Stream.generate(containingObject::getAndIncrement)...

i.e. this method reference falls into the second category of method references - Reference to an instance method of a particular object.

You should note that the AtomicInteger instance creation is not part of the implementation of the IntSupplier. The Java 7 equivalent would be:

AtomicInteger aint = new AtomicInteger(1);
IntStream.generate(new IntSupplier() {

    @Override
    public int getAsInt() {
        return aint.getAndIncrement();
    }
})...

.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!