Skip to main content
gamedev.net
🔒 Locked

[java] Something like a pointer to member?

Started by bilsa 0 replies 300+ views
Original Post
bilsa
bilsa
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!
princec
princec
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;
}
}
}
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.