问题描述
这可能是一些常见而微不足道的事情,但我似乎很难找到具体的答案.在 C# 中有一个委托的概念,它与 C++ 中的函数指针的思想密切相关.Java 中是否有类似的功能?鉴于指针有些缺失,最好的方法是什么?需要明确的是,我们在这里谈论的是头等舱.
This may be something common and trivial, but I seem to be having trouble finding a concrete answer. In C# there is a concept of delegates, which relates strongly to the idea of function pointers from C++. Is there a similar functionality in Java? Given that pointers are somewhat absent, what is the best way about this? And to be clear, we're talking first class here.
推荐答案
Java 类函数指针功能的习惯用法是一个实现接口的匿名类,例如
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
更新:以上在 Java 8 之前的 Java 版本中是必需的.现在我们有更好的替代方案,即 lambdas:
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
和方法参考:
list.sort(MyClass::isGreaterThan);
这篇关于Java 中的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!