[英]How does java's double colon operator refer non-static method using class name
I have written a code like this:我写了这样的代码:
public class MyClass implements Comparable{
int value;
MyClass(int value){
this.value = value;
}
public static void main(String[] args) {
MyClass obj1 = new MyClass(30);
MyClass obj2 = new MyClass(5);
MyClass obj3 = new MyClass(15);
List<MyClass> classList = new ArrayList<>();
classList.add(obj1);
classList.add(obj2);
classList.add(obj3);
List<MyClass> list2 =classList.stream().sorted(MyClass::compareTo).collect(Collectors.toList());
list2.stream().forEach(x-> System.out.println(x.value));
}
@Override
public int compareTo(Object o) {
MyClass obj = (MyClass)o;
if(this.value<obj.value){
return +1;
}else return -1;
}
}
This code compiles successfully gives me the correct output as expected-这段代码编译成功给了我预期的正确输出-
30
15
5
I have 2 questions我有 2 个问题
How are we able to refer non-static method compareTo using Myclass(classname)?我们如何使用 Myclass(classname) 引用非静态方法 compareTo? Shouldn't we be expected to use object of my class to refer compareTo()?
难道我们不应该使用我的类的对象来引用 compareTo() 吗?
How are we able to use compareTo() method which takes only 1 parameter, whereas sorted()
expects Comparator Interface whose abstract class compare()
takes 2 parameters?我们如何能够使用只接受 1 个参数的 compareTo() 方法,而
sorted()
期望其抽象类compare()
接受 2 个参数的 Comparator 接口?
The Stream method sorted
takes a Comparator<T>
as parameter. sorted
的 Stream 方法将Comparator<T>
作为参数。 This is a functional interface, so you can use a lambda expression or method reference as parameter that adheres to this interface.这是一个函数式接口,因此您可以使用 lambda 表达式或方法引用作为遵循此接口的参数。 The method signature is as follows:
方法签名如下:
int compare(T var1, T var2);
So, for example, the following lambda expression is valid:因此,例如,以下 lambda 表达式是有效的:
(MyClass a, MyClass b) -> a.compareTo(b)
A method reference can refer to static methods, but in this specific context, the type of the method reference can also replace the first parameter, so the following expression is equivalent to the above:方法引用可以引用静态方法,但是在这个特定的上下文中,方法引用的类型也可以代替第一个参数,所以下面的表达式等价于上面的:
MyClass::compareTo
Similarly, you can do the following:同样,您可以执行以下操作:
(String a, String b) -> a.equals(b)
String::equals
Or things like this:或者是这样的:
(String a) -> "b".equals(a)
"b"::equals
List list2 =classList.stream().sorted(MyClass::compareTo).collect(Collectors.toList()); List list2 =classList.stream().sorted(MyClass::compareTo).collect(Collectors.toList());
In this line you have used stream.sorted which still is a stream then you have called compareTo method in MyClass for each stream element.在这一行中,您使用了仍然是流的 stream.sorted,然后您在 MyClass 中为每个流元素调用了 compareTo 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.