::是java8的新特性,叫做方法引用
由於lamdba表達式中不可以直接執行方法,所以出現了方法引用
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
// 實例方法的方法引用
ArrayList<String> list = new ArrayList();
list.add("aa");
list.add("bb");
list.add("cc");
// list.forEach(path-> System.out.println(path)); 和下面的輸出是一樣的
// 消費型函數式接口 path作為參數傳遞
// 因為forEach要接收一個lambda表達式,所以要將method方法轉換為方法引用
list.forEach(new MethodQuote()::method1);
System.out.println("=================這是一個分隔符=================");
// 靜態的方法引用
list.forEach(MethodQuote::method2);
System.out.println("=================這是一個分隔符=================");
}
}
class MethodQuote{
private String name;
public MethodQuote() {
}
public MethodQuote(String name) {
this.name = name;
}
public void method1(String path){
System.out.println(path);
}
public static void method2(String path){
System.out.println(path);
}
public static void main(String[] args) {
// 類構造器引用語法 這里 並沒有實現接口
Interface methodQuote=MethodQuote::new;
MethodQuote mq=methodQuote.create("java");
System.out.println(mq.name);
}
}
interface Interface{
MethodQuote create(String name);
}