Search code examples
javacomparable

How To implement Compare to method for custom object


In java i have an arrayList of my own(implemented) i have a sort method so i need 'compareTo' method thats why i implemented Comparable and made the class abstract. But if i use arraylist from main i have to implement compare to method .But I cant understand how i can implement this.( I have a restriction, for example if i have a arraylist of 'order' class i cant implement comparable in order class)

Arraylist

public abstract class ArrayList<T>  implements  Comparable

inside sort function

    Comparable left=(Comparable)L[i];
    Comparable right=(Comparable)R[j];
    for(int k=start;k<=end;k++)
    {
        if(left.compareTo(right)<=0)
        {
            array[k]=L[i];
            i++;
            left=(Comparable)L[i];

        }

From main

ArrayList<Order> order = new ArrayList<Order>() {
        @Override
        public int compareTo(Object o) {
            if(this)// but this main is not order class this is arraylist class
            return 0;
        }
    };

Solution

  • Why does your ArrayList implements Comparable? Do you want to compare 2 lists? If you want to compare or order the elements of the list, the elements should be Comparable, but not the list itself.

    You can also have a look to the following issue: How to use Comparator in Java to sort You will then have to implement a Comparator for your class Order (not the interface Comparable)