Search code examples
javacollectionscomparable

How can we sort elements of Objects just by implementing Comparable interface?


Here is the example code:

public class test {

    public static void main(String[] args) {
        ArrayList<Point> list = new ArrayList<Point>();
        list.add(new Point(1));
        list.add(new Point(4));
        list.add(new Point(2));
        list.add(new Point(3));
        list.add(new Point(2));
        Collections.sort(list);
    }

}

So I don't know why I can't use the Collections.sort until I add the compareTo method of Comparable interface to class Point.

I also do not know how the method compareTo sorting elements just by return -1, 0 and 1.

If anyone has any idea please explain to me.


Solution

  • So I don't know why I can't use the Collections.sort until I add the compareTo method of Comparable interface to class Point.

    Because java has no idea why a new Point(1) should sort above or below a new Point(2).

    I also do not know how the method compareTo sorting elements just by return -1, 0 and 1.

    Let's say I give you a bag with a pieces of paper inside. Each paper lists a name and a phone number and I want you to write a phone book that is ordered, but you don't know which ordering.

    All you can do is ask for any 2 notes which one is 'higher' than the other.

    Then you can do the job: Let's say you have sorted 12 notes so far.

    Then take the 13th note from the bag, and ask me if it is higher or lower than the 6th note in your pile. I say 'higher'. So you ask me about the 9th, I say higher. You ask about the 11th, I say lower. You ask me about the 10th, I say higher.

    That's all you needed to know> You slide the note in between the 10th and 11th and move on to the 14th note.

    See? An oracle that just answers the question: Given these 2 notes, tell me: Is this one lower than that one, higher, or the same? - And that's all you need.

    You're also out of date, this code and the notion of writing your own compareTo is rather old. It's much simpler now:

    list.sort(Comparator.comparingInt(Point::getValue));
    

    is all you need. will sort by running p.getValue() on every point which produces an int value, and then sorting the points by treating a lower int as meaning that the point 'comes before' a point with a higher value.

    You can then use secondary sorting orders (if 2 points have the same value, sort on their ID instead), define where null values should fit on the line, reverse the order, etcetera.

    No need to mess with -1, 0, and +1.