Okay suppose I have an array of objects that look like this:
obj(from, to)
I want to to sort that array by comparing from and to. An example of what I want done:
Suppose I have objects with these parameters
(0,2) (2,4) (0,3) (4,5) (2,3)
I want the objects to be sorted in this order:
(0,2) (0,3) (2,3) (2,4) (4,5)
I want the first two “from” variables compared and the lower one placed in front. If they are equal then I want the second pair of number compared. To do this I created a compare method
public int compare (EdgeI e1, EdgeI e2) {
if(e1.from < e2.from) { return -1; }
else if(e1.from == e2.from) {
if(e1.to < e2.to) { return -1; }
else if(e1.to == e2.to) { return 0; }
else if(e1.to > e2.to) { return 1; }
}
return 1;
}
Would this work? And if so, how would I run this sort through the array?
Thanks for any help.
EDIT
public class mySorter implements Comparator <EdgeI> {
public int compare(EdgeI e1, EdgeI e2) {
if(e1.from < e2.from) { return -1; }
else if(e1.from == e2.from) {
if(e1.to < e2.to) { return -1; }
else if(e1.to == e2.to) { return 0; }
else if(e1.to > e2.to) { return 1; }
}
return 1;
}
public void sorterM () {
Collections.sort(tet2, new mySorter());
}
}
I get the error Collections cannot be resolved, and tet2 cannot be resolved. Tet2 is a List delcared public in another class.
What you can do is create a class which implements
Comparator<Edge>. You can then use your compare method to implement the method from the interface.After you have done this you can use the comparator to sort a list of
Edgeobjects usingCollections.sort().This would look something like this:
Here is the javadoc on Comparator and Collections.sort.
If you have an array instead of a list you can instead use Array.sort in the same way as
Collections.sort.