WebStormer
WebStormer

Reputation: 256

How return a generic array of <T extends Comparable<? super T>> in Java?

I'm trying to figure it out why my IDE is alerting me of this:

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

The code is in the following snippet:

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;
}

The CleverSearcherGenerics that extends the SearcherGenerics:

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];
  }
}

Upvotes: 2

Views: 596

Answers (1)

mentallurg
mentallurg

Reputation: 5207

The new generic definition in the methods getArray() and findElement() is not needed. You have already defined T on the class level. Define your methods as follows:

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

abstract public T findElement() throws IndexingError;

Upvotes: 3

Related Questions