函数引用以 ()-> 语法定义 java 中的函数,用于将方法或构造函数作为参数传递。优点包括简洁性、可读性和维护性。它们主要用于定义事件处理程序、比较器和线程。
如何使用函数引用定义 Java 中的函数
函数引用是一种简洁的方式,用于在 Java 中定义函数,它允许我们将方法或构造函数作为参数传递。它通过 ()-> 语法来表示,其中 -> 左侧表示输入参数(如果有),右侧表示要调用的方法或构造函数。
使用函数引用
函数引用可以用来取代需要函数对象的地方,例如:
优点
与匿名内部类相比,函数引用具有以下优点:
语法
函数引用有两种主要形式:
ClassName::methodName
ClassName::new
实战案例
事件处理程序
以下示例展示了如何使用函数引用定义按钮点击事件处理程序:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonExample {
private static void main(String[] args) {
// 使用 lambda 表达式定义事件处理程序
ActionListener listener1 = (ActionEvent e) -> System.out.println("Lambda!");
// 使用函数引用定义事件处理程序
ActionListener listener2 = ButtonExample::onButtonClick;
// 添加事件处理程序到按钮
JButton button = new JButton("Click Me!");
button.addActionListener(listener1);
button.addActionListener(listener2);
}
private static void onButtonClick(ActionEvent e) {
System.out.println("函数引用!");
}
}比较器
以下示例展示了如何使用函数引用定义一个比较器:
import java.util.Comparator;
public class ComparatorExample {
private static void main(String[] args) {
// 使用 lambda 表达式定义比较器
Comparator comparator1 = (String s1, String s2) -> s1.compareTo(s2);
// 使用函数引用定义比较器
Comparator comparator2 = String::compareTo;
// 比较两个字符串
int result = co
mparator1.compare("A", "B");
System.out.println(result); // 返回负数,因为 "A" 小于 "B"
}
} 线程
以下示例展示了如何使用函数引用定义一个线程:
import java.lang.Thread;
public class ThreadExample {
private static void main(String[] args) {
// 使用 lambda 表达式定义线程
Thread thread1 = new Thread(() -> System.out.println("Lambda!"));
// 使用函数引用定义线程
Thread thread2 = new Thread(ThreadExample::run);
// 启动线程
thread1.start();
thread2.start();
}
private static void run() {
System.out.println("函数引用!");
}
}