You have an ArrayList of objects that you need to be sorted by their
integer member variables
Solution:
Let's say you have a Record class with the following members: int id, int weight;
class Record {
public Record(int i, int w){
this.id =i;
this.weight = w;
}
int id;
int weight;
public int getId() {
return id;
}
public int getWeight() {
return weight;
}
}
You have an ArrayList of objects of the Record class that need to be sorted by weight. To make it possible, the Record class needs to implement the Comparable interface which mandates the use of the compareTo method with the following signature:
public int compareTo(Object o)
That means we need to add the following code to the Record class:
public int compareTo(Object o) {
int weight = ((Record) o).getWeight();
return weight - this.weight;
}
We use
weight - this.weight for descending order andthis.weight - weight for ascending order.Once we have the proper method in the Record class, all we need to do is use the sort method
of the Collections class.
Collections.sort (myArrayList);
No comments:
Post a Comment