You need to implement Comparable
or Comparator
interface for your purpose. sorting user defined objects with Comparator and sorting user defined objects with comparable
You can learn the difference between these two by reading these tutorials
Consider you want your products to be sorted using its price then make your Product
implement Comparable
as follows
public class Product implements Comparable<Product>{
public int compareTo(Product other){
// your logic here
}
}
But hold on... now that we have already implemented Comparable
interface to sort the objects using its price, how can we sort them using another sort sequence? We only have one compareTo()
method and we can't write separate sort sequence in the same class. Here comes the role of Comparator
. With Comparator
, you can define multiple sort sequences.
Suppose we want to sort using its price, then:
public class PriceSorter implements Comparator<Product>{
public int compare(Product one, Product another){
int returnVal = 0;
if(one.getPrice() < another.getPrice()){
returnVal = -1;
}else if(one.getPrice() > another.getPrice()){
returnVal = 1;
}else if(one.getPrice() == another.getPrice()){
returnVal = 0;
}
return returnVal;
}
}
and you want another sort sequence, now for its name, then:
public class NameSorter implements Comparator<Product>{
public int compare(Product one, Product another){
return one.getName().compareTo(another.getName());
}
}
Now, when you want to sort using price, then
Collections.sort(yourList,new PriceSorter());
If you want to sort using name, then
Collections.sort(yourList, new NameSorter());
The second argument takes the Comparator
instance which makes the sort method know what logic to follow while sorting objects
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…