Archived

This topic is now archived and is closed to further replies.

bilsa

pointer to member in JAVA - something similar?

Recommended Posts

bilsa    157
Hello! In my design I have a relation like this: 1. DataStorage object. This object decides how to store the data, wether in a Tree or Linked list or Vectro etc... It also decides how much data to store in this DataStorage object. For eg. it can store 1 object or 2 or 3, all up to the programmer. It stores the objects as a Pair - So the second data in the Pair might in turn also be a Pair... 2. Sorter object. This object sorts a DataStorage object. But I want it to be able to sort on the object of my choice from the DataStorage object. In one case I might want to sort on the 1''st object but in another case I might want to store on the 2''nd object or on the 3''rd. So basically what I need is to do something like this:
//aka C++ syntax...

sort(&Pair::first, dataStorageObject);
sort(&Pair::second, dataStorageObject);

//So I want to be able to send as an argument which data to sort

//on, like in the C++ pointer to member variant.

I know I could write a new sort function for each data I want to sort on, but thats what I want to eliminate... Thx for the help guys!

Share this post


Link to post
Share on other sites
overnhet    122
If you use standard Java classes for your collection, you can benefit from java.util.Collections.sort() : you''ll simply need to create a custom Comparator that compares either the first or the second object of your pairs.

Share this post


Link to post
Share on other sites
paulecoyote    1065
Easy misconception - ALL your own classes (anything that isn''t a primitive) are ALWAYS passed by reference. Primitives (eg ints) are always passed by value. To do swap functions you have to wrap primitives; eg int == Integer.

This means a swap function is possible with 2 wrapped up Integers, but impossible with two ints.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
quote:
Original post by paulsdsrubbish
Easy misconception - ALL your own classes (anything that isn''t a primitive) are ALWAYS passed by reference. Primitives (eg ints) are always passed by value. To do swap functions you have to wrap primitives; eg int == Integer.

This means a swap function is possible with 2 wrapped up Integers, but impossible with two ints.



Which is not really a big loss, it just removes a few headaches.

Share this post


Link to post
Share on other sites