T.S*_*T.S 2 java java-8 method-reference
我不明白之间的区别
this::myMethod
Run Code Online (Sandbox Code Playgroud)
和
ClassName::myMethod
Run Code Online (Sandbox Code Playgroud)
当这是ClassName类的实例时.
我认为在这两种情况下我都会调用该方法myMethod
并将myObject
其作为myMethod
方法的参数运行,但我认为存在差异.它是什么?
this::myMethod
指的是您在其代码中放置的实例myMethod
的特定实例.ClassName
this::myMethod
ClassName::myMethod
可以指静态方法或实例方法.如果它引用实例方法,则可以在ClassName
每次调用它时在不同的实例上执行.
例如:
List<ClassName> list = ...
list.stream().map(ClassName::myMethod)...
Run Code Online (Sandbox Code Playgroud)
将myMethod
每次执行ClassName
列表的不同成员.
这是一个模式详细示例,显示了这两种方法参考之间的区别:
public class Test ()
{
String myMethod () {
return hashCode() + " ";
}
String myMethod (Test other) {
return hashCode() + " ";
}
public void test () {
List<Test> list = new ArrayList<>();
list.add (new Test());
list.add (new Test());
System.out.println (this.hashCode ());
// this will execute myMethod () on each member of the Stream
list.stream ().map (Test::myMethod).forEach (System.out::print);
System.out.println (" ");
// this will execute myMethod (Test other) on the same instance (this) of the class
// note that I had to overload myMethod, since `map` must apply myMethod
// to each element of the Stream, and since this::myMethod means it
// will always be executed on the same instance of Test, we must pass
// the element of the Stream as an argument
list.stream ().map (this::myMethod).forEach (System.out::print);
}
public static void main (java.lang.String[] args) {
new Test ().test ();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
2003749087 // the hash code of the Test instance on which we called test()
1747585824 1023892928 // the hash codes of the members of the List
2003749087 2003749087 // the hash code of the Test instance on which we called test()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
84 次 |
最近记录: |