Sorting ArrayList special issue
I have a class Location that takes 3 parameters x y and z. I have an arraylist of Location and I am trying to sort these locations by ascending order.
Now I read about arraylist.sort() but how can I sort the locations according to a certain parameter, say the y parameter???
thanks
Re: Sorting ArrayList special issue
Object Ordering (The Java™ Tutorials > Collections > Interfaces)
Collections (Java Platform SE 6), java.util.Comparator)
Comparator (Java Platform SE 6)
Code:
Collections.sort(yourArrayList, new Comparator<Location>() {
@Override
public int compare(Location o1, Location o2) {
return ..... //your logic here...
}
});
Re: Sorting ArrayList special issue
well that's what I've been trying and I can't figure it out (sorry im a beginner)
I tried
Code:
final Comparator<AddressLoc> highestLevel =
new Comparator<AddressLoc>() {
@Override
public int compare(AddressLoc o1, AddressLoc o2) {
return o1.getZ().compareTo(o2.getZ());
}
};
and I get "Cannot invoke compareTo(int) on the primitive type int"
Re: Sorting ArrayList special issue
Yes because you can`t invoke methods on primitives!
You could write return o1.getZ() - o2.getZ();
but that could lead to a wrong result.
but you could use some if statements (or ternary operator)?
if(o1.getZ() == o2.getZ()) return .... else if(o1.getZ() > o2.getZ()) return .... else return ....