Search code examples
javainterfacecomparable

Java comparable interface compareTo(Object o), what is object o?


Beginner, can't seem to wrap my head around this.

Item Class

public class Item implements Comparable {

private int number;
private String description;

public Item(int num, String descript){
    this.number = num;
    this.description = descript;
}

public int getNumber(){
    return number;
}

public String getDescription(){
    return description;
}

@Override public int compareTo(Object o){
    Item i = (Item) o;
    if(this.getNumber() < i.getNumber())
        return -1;

    if(this.getNumber() > i.getNumber())
        return 1;

    return 0;
}

}

Main method

Item[] items = new Item[3];
    items[0] = new Item(102, "Duct Tape");
    items[1] = new Item(103, "Bailing wire");
    items[2] = new Item(101, "Chewing Gum");

    Arrays.sort(items);

    for (Item i : items){
        System.out.println(i.getNumber() + ": " + i.getDescription());
    }

When the main method instantiate items[0] = new Item(102, "Duct Tape"); Which goes through Item constructor to set current variable number, description.

My problem is I can't seem to understand what is being passed in the compareTo argument, therefore I can't seem to understand this.getNumber() < i.getNumber() is doing...

Return a negative number if current object is less than passed object?

any help is much appreciated.


Solution

  • My problem is I can't seem to understand what is being passed in the compareTo argument

    Array.sort uses the compareTo method to know how to compare pairs of items from the array.

    Your sort method assumes that it will only be called with instances of Item, and that's all Array.sort will pass along to compareTo assuming that your array only holds instances of Item.

    You will get a runtime exception if compareTo is ever invoked with the item being compared to not being an instance of Item.

    I can't seem to understand this.getNumber() < i.getNumber() is doing...

    It's comparing two instance of Item based on the value of getNumber, that is, the value of their number fields. It assumes that two instances of Item are equal if Item.number is the same for each instance, otherwise one is less than the other if its Item.number is less than the other's Item.number.