Sunday, November 9, 2014
Arrays.sort(fruits, Fruit.FruitNameComparator) - Fruit static object FruitNameComparator
import java.util.Arrays;
public class ComparatorTest {
public static void main(String[] args){
Fruit fruit1 = new Fruit("banana",1);
Fruit fruit2 = new Fruit("apple",2);
Fruit fruit3 = new Fruit("orange",3);
Fruit[] fruits = {fruit1, fruit2, fruit3};
// we can write comparator based on properties
Arrays.sort(fruits,Fruit.FruitNameComparator);
for (Fruit fruit: fruits){
System.out.println(fruit.getName());
}
}
}
import java.util.Comparator;
public class Fruit implements Comparable{
public static final Comparator<Fruit> FruitNameComparator = new Comparator<Fruit>(){
@Override
public int compare(Fruit fruit1, Fruit fruit2) {
// fruit1.getName() is String, String.compareTo
// String, Integer, Double all have compareTo()
return fruit1.getName().compareTo(fruit2.getName());
}
};
public Fruit(String name, int quantity) {
super();
this.name = name;
this.quantity = quantity;
}
String name;
int quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
// comparable means this object is comparable so it can compareTo other object
@Override
public int compareTo(Object compareFruit) {
int compareFruitQuantity = ((Fruit)compareFruit).getQuantity();
//ascending order
return this.getQuantity() - compareFruitQuantity;
}
}
OUTPUT
apple
banana
orange
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment