Cannot find compareTo when receiving comparable Object[]

99封情书 提交于 2021-01-25 07:19:08

问题


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?


回答1:


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.




回答2:


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()).



来源:https://stackoverflow.com/questions/35760381/cannot-find-compareto-when-receiving-comparable-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!