Archived

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

[java] Something like a pointer to member?

This topic is 5014 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
You must provide an object that implements the Comparator interface to do what you want. I suggest that the closest sensible analogy to what you want to do is to create static final Comparators in your class that sort by the different fields:

class X {
int a, b;
public static final Comparator SortByA = new Comparator() {
public int compare(Object a, Object b) {
X xa = (X) a, xb = (X) b;
if (xa.a < xb.a) {
return -1;
} else if (xa.a > xb.a) {
return 1;
} else {
return 0;
}
}
}
public static final Comparator SortByB = new Comparator() {
public int compare(Object a, Object b) {
X xa = (X) a, xb = (X) b;
if (xa.b < xb.b) {
return -1;
} else if (xa.b > xb.b) {
return 1;
} else {
return 0;
}
}
}
}

Share this post


Link to post
Share on other sites