Start New Discussion within our Software Development Community

Can somebody explain me the use of "Delegate" and its equivalent in java... I am learning java programming and has encountered a C# program which use "Delegate" and pass on functions as arguments to another function.... I am trying to modify the C# program for use in java...

You'd be better asking this in the Java section. Java has no easy way of replicating delegates from C#.

At best, a delegate is a single method interface. I believe that there is a "Delegator" pattern for Java, but I don't know much about it.

There is no direct equivalent for delegate in Java, that is you can't pass methods as arguments to other methods in Java. What you do instead is to create a one-method interface and then implement it and pass an instance of it as a parameter to the given method.

So for example sorting methods take a Comparator<T> object as an argument. Comparator<T> is an interface containing the single method int compare(T,T)). The sorting methods in C# either take an IComparer<T> (which is a one-method interface just like Comparator<T>) or a Comparisson<T> (which is a delegate) as an argument. In Java the delegate option is just not available.

This article has been dead for over six months. Start a new discussion instead.