1,105,534 Community Members

"delegate" equivalent in java

Member Avatar
abra_ka_dabra
Light Poster
36 posts since May 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
Ketsuekiame
Posting Virtuoso
1,676 posts since May 2010
Reputation Points: 793 [?]
Q&As Helped to Solve: 231 [?]
Skill Endorsements: 27 [?]
 
0
 

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.

Member Avatar
abra_ka_dabra
Light Poster
36 posts since May 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
sepp2k
Posting Pro in Training
464 posts since Jul 2012
Reputation Points: 300 [?]
Q&As Helped to Solve: 97 [?]
Skill Endorsements: 23 [?]
 
0
 

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.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article