sách gpt4 ai đã đi

Tại sao các tham chiếu phương thức lại tương thích với các giao diện chức năng có số lượng tham số khác nhau?

In lại 作者:行者123 更新时间:2023-12-02 07:57:23 27 4
mua khóa gpt4 Nike

我知道,如果引用的方法采用与功能接口(interface)相同数量的参数并返回相同的类型,则方法引用可用于实现功能接口(interface),但为什么在某些情况下引用的方法的参数数量与函数接口(interface)的参数数量不同功能接口(interface)但仍然兼容?

我有一个简单的 BiConsumer,我尝试使用方法引用来实现它。我知道只要参数数量匹配,我也可以使用 lambda 表达式。我将展示代码以清楚地解释它。

Tôi có một cáiBiConsumer<>, ? super String>我想实现。

Lambda 表达式的实现方法是:

BiConsumer<>, ? super String> b = (firstArg,secondArg) -> firstArg.add(secondArg);因为它们都需要 2 个输入参数,所以没有问题。

但是为什么BiConsumer<>, ? super String> a = ArrayList::add;还兼容吗? thêm vào ArrayList 上的方法只需要 1 个输入参数,但功能接口(interface)需要 2 个。

任何答案将不胜感激。谢谢!

1 Câu trả lời

15.12.2.1. Identify Potentially Applicable Methods

A method reference expression (§15.13) is potentially compatible with a functional interface type T if, where the arity of the function type of TN, there exists at least one potentially applicable method when the method reference expression targets the function type with arity N (§15.13.1), and one of the following is true:

  • The method reference expression has the form ReferenceType :: [TypeArguments] Identifier and at least one potentially applicable method is either (i) static and supports arity N, or (ii) not static and supports arity n-1.

您要使用的函数类型的参数为 2

void accept(T t, U u);

并且 ArrayList::add 引用的方法的数量为 1,并且它不是静态的。这使得它具有潜在的适用性。

关于java - 为什么方法引用与具有不同参数数量的功能接口(interface)兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57828856/

27 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com