• Post Reply Bookmark Topic Watch Topic
  • New Topic

No function pointers unless wrapped in object?  RSS feed

 
Aiman Ashraf
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am new to java and I am finding it real weird.

I want my class to be able to sort arbitrary objects. I want them to send in any function which takes 2 objects as parameters and returns an integer.
I can write a MyComparable interface and ask all classes to implement it. Fine but I don't want to force each and every class to implement the MyComparable interface.

Is there a workaround for this problem in java?
In C++ this is done by function pointer. In C# this is done by delegates.

Any help would be appreciated.
Thanks
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No such thing as function pointers in Java.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using the existing Comparable interface is the correct approach to this problem.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Using the existing Comparable interface is the correct approach to this problem.


Actually, the java.util.Comparator interface sounds more like what is needed.

Henry
 
Aiman Ashraf
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
Actually, the java.util.Comparator interface sounds more like what is needed.

Henry


Hmm, Comparator sounds better than Comparable because we wont force every class to implement an interface at least.
The problem is that most of these classes already have a method for comparison, so writing Comparator implementations seems like a lot of duplicate code. I agree that it's the proper way though.

BTW, I found http://java.sun.com/docs/white/delegates.html and I must say that it surely aint written in the most unbiased tone that I've seen.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree. I did think while I was going round town today that I had forgotten about Comparator.
 
Embla Tingeling
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aiman Ashraf wrote:Fine but I don't want to force each and every class to implement the MyComparable interface.


You can use templates.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!