Function Pointers in Java

dreadwail picture dreadwail · Jul 2, 2009 · Viewed 159.9k times · Source

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.

Answer

Michael Borgwardt picture Michael Borgwardt · Jul 2, 2009

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
    }
});

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));

and method references:

list.sort(MyClass::isGreaterThan);