对特定类型的任意对象的实例方法的方法引用

huangapple go评论79阅读模式
英文:

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
  1. 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是对一个单一参数的方法的方法引用,它将给定的StringString"a"进行比较。隐式参数始终等于"a"。

一个Comparatorcompare方法需要两个给定的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

huangapple
  • 本文由 发表于 2020年8月16日 19:51:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63436533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定