如何返回<T的通用数组扩展Comparable <? Java中的超级T >>?

时间:2019-12-15 23:38:23

标签: java arrays generics

我试图弄清楚为什么我的IDE提醒我这一点:

Incompatible types: required T[], found T[]

代码在以下代码段中:

public abstract class SearcherGenerics<T extends Comparable<? super T>> {

  private T[] array; 
  private int k; 

  SearcherGenerics(T[] array, int k) {
    this.array = array;
    this.k = k;
  }

  public <T extends Comparable<? super T>> T[] getArray() {
    return array;
  }

  int getIndex() { return k; }


  abstract public <T extends Comparable<? super T>> T findElement() throws IndexingError;
}

扩展了SearcherGenerics的CleverSearcherGenerics:

public class CleverSearcherGenerics<T extends Comparable<? super T>> extends SearcherGenerics<T> {

  CleverSearcherGenerics(T[] array, int k) {
    super(array, k);
  }

  @Override
  public <T extends Comparable<? super T>> T findElement() throws IndexingError {
    T[] bigArray = getArray();
    int k = getIndex();

    if (k <= 0 || k > bigArray.length) {
      throw new IndexingError();
    }

    T[] smallArray = Arrays.copyOfRange(bigArray, 0, k);
    Arrays.sort(smallArray);


    for (int i = k; i < bigArray.length; i++) {
      if (bigArray[i].compareTo(smallArray[0]) > 0){
        smallArray[0] = bigArray[i];

        int j = 0;
        while ((j < k - 1) && (smallArray[j].compareTo(smallArray[j + 1]) > 0)) {
          T temp = smallArray[j];
          smallArray[j] = smallArray[j + 1];
          smallArray[j + 1] = temp;
          j++;
        }
      }
    }
    return smallArray[0];
  }
}

1 个答案:

答案 0 :(得分:3)

不需要方法getArray()findElement()中的新通用定义。您已经在课程级别定义了T。如下定义您的方法:

public T[] getArray() {
    return array;
}

abstract public T findElement() throws IndexingError;