Comparable Example

Below is an example on how to use Comparable


import java.util.TreeSet;

class Item implements Comparable{

	private String name;
	private int quantity;

	public Item(String name, int quantity) {
		super();
		this.name = name;
		this.quantity = 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;
	}

	public String toString()
	{
		return " "+name+" "+quantity;
	}

	public int compareTo(Item compareItem) {

		int compareQuantity = ((Item) compareItem).getQuantity();

		return this.quantity - compareQuantity;
	}
}

public class MyTreeSetComparable {

    public static void main(String a[]){
        TreeSet ts = new TreeSet();

        Item it1 = new Item("Banana", 21);
        Item it2 = new Item("Orange", 2);
        Item it3 = new Item("Apple", 56);
        Item it4 = new Item("Sapota", 11);
        Item it5 = new Item("PIneapple", 6);

        ts.add(it1);
        ts.add(it2);
        ts.add(it3);
        ts.add(it4);
        ts.add(it5);

        System.out.println(ts);
    }
}

You may also like to read:
Comparator example
Difference between Comparator and Comparable interfaces

2 thoughts on “Comparable Example”

Leave a Reply