错误:Java:31找不到符号

时间:2014-04-03 01:16:22

标签: java generics types

所以我在尝试编译我的java程序时遇到了这个错误

./QuickSort.java:31: cannot find Symbol
Symbol : method compareTo(T)
location: class java.lang.Object
      while(x<high && (arrValues[x].compareTo(arrValue))==1){
                                   ^

第35行也是如此。

我创建了一个通用的类QuickSort,在这种情况下,T值是Person。第31行和第35行位于函数divide

class QuickSort<T> extends AbstractSorter { 
private T[] values;
private int dataCount;

QuickSort(){
    System.out.println("INITILAZIED");
}

public void switchValues(T[] arrValues, int index1, int index2){
    T temporary = arrValues[index1];
    arrValues[index1] = arrValues[index2];
    arrValues[index2] = temporary;
}


public void actualSort(T[] arrValues, int low, int high){
    if(low<high){
        int newHigh = divide(arrValues,low,high);
        actualSort(arrValues,low,newHigh);
        actualSort(arrValues,low+1,high);
    }
}

public int divide(T[] arrValues, int low, int high){
    T arrValue = arrValues[low];
    int x = low - 1;
    int y = high +1;

    while(true){
        ++x;
        while(x<high && (arrValues[x].compareTo(arrValue))== 1){
            ++x;
        }
        --y;
        while(y>low && (arrValues[y].compareTo(arrValue)) == -1){
            --y;
        }
        if(x<y){
            switchValues(arrValues,x,y);
        }
        else
            return y;
    }
}       

public void doSort(){ 
    this.actualSort(values, 0, values.length-1);
}

public void sortArray(int orderOfSort, T[] arrayOfValues){
    this.values = arrayOfValues;
    this.doSort();
    System.out.println("IT WORKED");
}   

我在这里有personTo方法。

    public int compareTo(Person a){ //1 signifies THIS is alphabetically first, 0 signifies equal, -1 signifies Person a is first
    if(this.lastName.compareTo(a.lastName) == 1){
        return 1;
    }
    else if(this.lastName.compareTo(a.lastName) == 0){
        if(this.firstName.compareTo(a.firstName) == 1){
            return 1;
        }
        else if(this.firstName.compareTo(a.firstName) == 0){
            return 0;
        }
        else{
            return -1;
        }
    }
    else{
        return -1;
    }

}

我不确定导致此错误的原因。 非常感谢您的帮助!!

1 个答案:

答案 0 :(得分:4)

您的值属于通用类型T。由于该类型没有边界,因此最不常见的基类型是Object,它没有compareTo()方法。正如评论中@ exception1所述,您需要将T类型的下限设置为Comparable<T>