Sunday, November 9, 2014

Arrays.sort(Fruit) - Fruit needs to implement Comparable

Comparable is java.lang.Comparable
Comparator is java.util.Comparator

Comparable means this object is Comparable, it can compareTo other object
Comparator means tool can compare two objects, so it has method compare(object1, object2)

Comparable compare based on single property 
Comparator could compare based on multiple properties


import java.util.Arrays;

public class ComparableTest {
   
    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};
       
        Arrays.sort(fruits);
       
        for (Fruit fruit:fruits){
            System.out.println(fruit.getName());
        }
    }

}

public class Fruit implements Comparable{
    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
banana
apple
orange

No comments:

Post a Comment