英文:
Method reference to an instance method of an arbitrary object of a particular type
问题
String[] arr = {"First", "Second", "Third", "Fourth"};
Arrays.sort(arr, String::compareToIgnoreCase); // 可以编译
Arrays.sort(arr, "a"::compareToIgnoreCase); // 无法编译
1) 为什么 "a"::compareToIgnoreCase 无法编译?如果我们可以说 String::compareToIgnoreCase 有一个隐式的 String 参数(this),为什么我们不能说 "a"::compareToIgnoreCase 有一个隐式的 "a" 参数?("a" 与 "First" 进行比较,"a" 与 "Second" 进行比较,依此类推)
英文:
String[] arr = {"First", "Second", "Third", "Fourth"};
Arrays.sort(arr, String::compareToIgnoreCase); //can compile
Arrays.sort(arr, "a"::compareToIgnoreCase); //can't compile
- why the "a"::compareToIgnoreCase cannot compile? if we can said String::compareToIgnoreCase has an implicit String argument (this), why we cannot said "a"::compareToIgnoreCase has an implicit "a" as argument? ("a" compare to "First", "a" compare to "Second".....)
答案1
得分: 2
"a"::compareToIgnoreCase
是对一个单一参数的方法的方法引用,它将给定的String
与String
"a"进行比较。隐式参数始终等于"a"。
一个Comparator
的compare
方法需要两个给定的String
实例。
也许如果你将方法引用写成lambda表达式,会更清晰:
Arrays.sort(arr, (a, b) -> a.compareToIgnoreCase(b)); // 可以编译
Arrays.sort(arr, (x) -> "a".compareToIgnoreCase(x)); // 不能编译,因为期望有两个参数的方法
英文:
"a"::compareToIgnoreCase
is a method reference to a method of a single argument, which compares a given String
to the String
"a". The implicit argument is always equal to "a".
A Comparator
's Compare
method requires two given String
instances.
Maybe if you write the method references as lambda expressions it would be clearer:
Arrays.sort(arr, (a,b) -> a.compareToIgnoreCase(b)); //can compile
Arrays.sort(arr, (x) -> "a".compareToIgnoreCase(x)); // can't compile, since a method with
// two arguments is expected
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论