Say I have a class that looks like this (get/set omited):
class InfoClass{
String name;
String place;
double distance;
}
And I create an array of my class from within my main activity that looks like this:
InfoClass[3] myInfoClass;
myInfoClass[0].name = "venue one";
myInfoClass[0].place = "place one";
myInfoClass[0].distance = 11.23234;
myInfoClass[1].name = "venue two";
myInfoClass[1].place = "place two";
myInfoClass[1].distance = 9.2345643;
myInfoClass[2].name = "venue three";
myInfoClass[2].place = "place three";
myInfoClass[2].distance = 5.23432;
How can I sort my array (myInfoClass[]) so that it is ordered by the distance member? i.e in the above example the array would be reversed because element [2] has the smallest distance and element [0] has the greatest distance?
Is there some function I can add to my class to do this or some other way?
this should work ..
public static void main(String[] args){
InfoClass[] dd = new InfoClass[3];
Arrays.sort(dd, new Comparator<InfoClass>(){
@Override
public int compare(InfoClass arg0, InfoClass arg1) {
// TODO Auto-generated method stub
if(arg0.distance == arg1.distance){
return 0;
}else if(arg0.distance < arg1.distance){
return -1;
}else{
return 1;
}
}
});
}
Modify your class and implement Comparable
interface if you don't want to use Comparator
its also preferable when by default you want to provide sorting to array/collection
of your objects then go for Comparable
class InfoClass implements Comparable<InfoClass> {
String name;
String place;
double distance;
@Override
public int compareTo(InfoClass o) {
return new Double(this.distance).compareTo(new Double(o.distance));
}
and then you can sort them
Arrays.sort(myInfoClass)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With