gpt4 book ai didi

java - 为什么这个 lambda 可以在这里使用,其中需要 Arrays.sort() 中的比较器

转载 作者:行者123 更新时间:2023-12-05 09:33:38 24 4
gpt4 key购买 nike

<分区>

我对 Lambda 不熟悉,教科书(简述 java)是这样说的:

Only certain types are eligible to be the target of a lambda .Target types are also called functional interfaces and they must:

  • Be interfaces
  • Have only one nondefault method(but may have other methods that are default)

这本书给了我一个例子:

File dir =new File("/src");
String[] fileList =dir.list((d,fName)->fName.endWith(".java"))

我知道这个 lambda 会转换成一个 FilenameFilter 接口(interface),它是一个 @FunctionalInterface 它确实符合书中的描述

enter image description here

不过,当 sort() 期望收到一个 Comparator

时,我可以在这里使用 lambda
        int n =12;
Function<String,String[]> f = (s) -> {
String[] ans = new String[n];();
for (int i = 0; i < n; i++) {
ans[i] = s;
}
return ans;};
Arrays.sort(f.apply("colin"),(String s1 ,String s2)->{
return s1.length() - s2.length();});

我查看了它的源代码,发现 Comparator 是一个 @FunctionInterface enter image description here

但是它有两个非默认的方法compareequals。和书上说的不一样。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com