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...

Recommended Answers

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.

Jump to Post

All 3 Replies

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.

Ok. Thanks. I would be posting it to java too.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.