pointer to member in JAVA - something similar?

Started by
2 comments, last by bilsa 20 years ago
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!
Advertisement
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.
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.
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.
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.

This topic is closed to new replies.

Advertisement