使用双冒号 - 静态和非静态方法引用之间的区别 [英] Use of double colons - difference between static and non-static method references

查看:163
本文介绍了使用双冒号 - 静态和非静态方法引用之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我的问题在这里得到了解答。总而言之,我对非静态方法引用的使用感到困惑。函数接口和引用方法有不同数量的参数。

My question here was answered. To summarize, I was confused about the usage of non-static method references. There the functional interface and referenced method have a different number of parameters.

我的问题是 comment 和接受的答案。

What answered my question is the comment and the accepted answer.

我目前正在阅读关于流减少方法的Java教程( https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html )。在那里,我发现了一段我认为错误的代码,所以我做了一个更简单的代码来确保。

I am currently reading the Java Tutorial about Stream reduction methods (https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html). There I found a piece of code that I thought was wrong, so I made a simpler code to make sure.

// B.java file
import java.util.*;

public class B 
{
  public static void main(String[] args)
  {
    List<Integer> zahlen = new LinkedList<Integer>();
    zahlen.add(1);
    zahlen.add(2);
    zahlen.add(3);
    Averager averageCollect = zahlen.stream()
      .collect(Averager::new, Averager::addcount, Averager::combine);
    System.out.println(averageCollect.average());
  }
}

// Averager.java from the official Java tutorial
public class Averager
{
    private int total = 0;
    private int count = 0;

    public double average() {
        return count > 0 ? ((double) total)/count : 0;
    }

    public void addcount(int i) { total += i; count++;}
    public void combine(Averager other) {
        total += other.total;
        count += other.count;
    }
}

我认为这不起作用的原因是因为该行:

The reason I thought this wouldn't work is because of the line:

Averager averageCollect = zahlen.stream()
  .collect(Averager::new, Averager::addcount, Averager::combine);

Stream.collect ( https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java .util.function.Supplier-java.util.function.BiConsumer-java.util.function.BiConsumer- )它说第二个参数是一个与功能接口匹配的函数 BiConsumer 是必需的,它有一个带有两个参数的抽象方法。但是 Averager.addcount Averager.combine 只有一个参数。

In the Java documentation for the Stream.collect (https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.function.Supplier-java.util.function.BiConsumer-java.util.function.BiConsumer-) it says that as the second parameter a function which matches the functional interface BiConsumer is required which has an abstract method with two arguments. But Averager.addcount and Averager.combine only have one parameter.

我还检查了lambda表达式:

I also checked with lambda expressions:

Averager averageCollect = zahlen.stream()
  .collect(Averager::new, (a,b) -> a.addcount(b), (a,b) -> a.combine(b));

此代码也有效,作为第二个和第三个参数,我有两个参数的函数。

This code also works and as the second and third parameter I have functions with two parameters.

为什么上面编写的代码确实有效,即使只给出了一个参数的函数?当我更改 Averager.addcount Averager.combine 这两个参数时,为什么会出现错误消息?

Why exactly does the code I wrote above work, even though functions with only one parameter were given? And why are there error messages when I change both Averager.addcount and Averager.combine to have two parameters like this?

public void addcount(Averager one, Integer i)
public void combine(Averager one, Averager other)

如果我这样做,我收到以下错误消息:

If I do that I get the following error message:

B.java:12: error: no suitable method found for collect(Averager::new,Averager::addcount,Averager::combine)
      .collect(Averager::new, Averager::addcount, Averager::combine);
      ^
    method Stream.collect(Supplier,BiConsumer,BiConsumer) is not applicable
      (cannot infer type-variable(s) R#1
        (argument mismatch; invalid method reference
          cannot find symbol
            symbol:   method addcount(R#1,Integer)
            location: class Averager))
    method Stream.collect(Collector) is not applicable
      (cannot infer type-variable(s) R#2,A
        (actual and formal argument lists differ in length))
  where R#1,T,R#2,A are type-variables:
    R#1 extends Object declared in method collect(Supplier,BiConsumer,BiConsumer)
    T extends Object declared in interface Stream
    R#2 extends Object declared in method collect(Collector)
    A extends Object declared in method collect(Collector)
1 error

请帮助我理解。

推荐答案

Averager averageCollect = zahlen.stream()
  .collect(Averager::new, Averager::addcount, Averager::combine);

这很好。它相当于

Averager averageCollect = zahlen.stream()
  .collect(() -> new Averager(),
           (myAverager, n) -> myAverager.addcount(n),
           (dst, src) -> dst.combine(src))

请记住每个非静态方法都有一个隐藏的参数。在这种情况下,它(正确地)将它绑定到累加器组合器回调的第一个参数。

Remember every nonstatic method has a hidden this parameter. In this case it is (correctly) binding this to the first argument of the accumulator and combiner callbacks.

它也适用于静态方法,例如:

It will also work with static methods such as:

public static void addcount(Averager a, int i) {
    a.total += i;
    a.count++;
}
public static void combine(Averager dst, Averager src) {
    dst.total += src.total;
    dst.count += src.count;
}

希望能让您更清楚发生的事情。

which hopefully makes it clearer what is happening.

但无需更改代码。

这篇关于使用双冒号 - 静态和非静态方法引用之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆