user1183772
user1183772

Reputation:

Cannot find compareTo when receiving comparable Object[]

The problem is the method is not sure a and b are comparable so the compiler throws a cannot find symbol for compareTo.

public class Merge {
    public ArrayList<Object> sorted(Object[] a, Object[] b) {

        int i, j, k;
        i = j = k = 0;
        ArrayList<Object> c = new ArrayList<>();
        while (i < a.length || j < b.length) {
            if (i == a.length) {
                for (j = j; j < b.length; j++) {
                    c.add(k, b[j]);
                    k++;
                }
                break;
            }
            else if (j == b.length) {
                for (i = i; i < a.length; i++) {
                    c.add(k, a[i]);
                    k++;
                }
                break;
            }
            else {
                if ( a[i].equals(b[j]) || a[i].compareTo(b[j]) < 0 ) {
                    c.add(k, a[i]);
                    i++;
                    k++;
                }
                else {
                    c.add(k, b[j]);
                    j++;
                    k++;
                }
            }
        }
        return c;
    }
}

The code works when used with Integer. I want to be able to use for example, sorted(a, b) being a = Person[] and b = Person[]. Of course with methods compareTo and equals inside Person.

Should I implement and extend comparable with an ObjectType inside this class and override compareTo?

Upvotes: 0

Views: 8180

Answers (2)

Darshan Mehta
Darshan Mehta

Reputation: 30809

To invoke compareTo() on an object, a class must implement Comparable interface and override compareTo() method. As Object class does not implement Comparable, the above code will always give you compilation error.

If you want to pass Person object only then you need to change the signature to accept Person[] array. If not then, you need to override toString() method (with a meaningful implementation) and change a[i].compareTo(b[j]) to a[i].toString().compareTo(b[j].toString()).

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533492

I suggest you change the signature to

public static <T extends Comparable<T>> List<T> sorted(T[] a, T[] b)

and you will be able to compare a[i].compareTo(b[i]) and a return a list of hte appropriate type.

Upvotes: 3

Related Questions