Ceylon Boy
Ceylon Boy

Reputation: 29

Error while trying to compare two elements (Java)!

class BubbleSort<T>  extends ArraySort<T>
{
    public void iSort(T[] inArray)  {
        int n = inArray.length;
        int k;
        for (int m = n; m >= 0; m--) {
            for (int i = 0; i < n - 1; i++) {
                k = i + 1;
                if (compare(inArray[i], inArray[k])) {
                    T temp;
                    temp = inArray[i];
                    inArray[i] = inArray[k];
                    inArray[k] = temp;
                }
            }
       }
       print(inArray);
    }
    public static <T extends Comparable<T>> boolean compare(T a, T b) {
        if (a.compareTo(b) > 0) {
            return true;
        } return false;
    }

I'm getting (T extends comparable < T >, T extends comparable < T >) in the type bubblesort< T > is not applicable for the arguments (T,T) error!

The quick fix is telling me to change method compare(T,T)< T > to compare(T,T), but that wouldn't resolve my problem. It works perfectly fine when I enter in actual value of elements, for example, compare(3, 5) or compare("hi", "hello") instead of compare(inArray[i], inArray[k]).

I would appreciate it a lot if someone could explain why it's doing that and give me a solution.

Upvotes: 1

Views: 50

Answers (1)

Jacob G.
Jacob G.

Reputation: 29680

You've already defined your class with a generic type T, so there's no point in declaring a separate one for the method:

class BubbleSort<T extends Comparable<T>> extends ArraySort<T> {
    public void iSort(T[] inArray) {
        int n = inArray.length;
        int k;
        for (int m = n; m >= 0; m--) {
            for (int i = 0; i < n - 1; i++) {
                k = i + 1;
                if (compare(inArray[i], inArray[k])) {
                    T temp;
                    temp = inArray[i];
                    inArray[i] = inArray[k];
                    inArray[k] = temp;
                }
            }
       }
       print(inArray);
    }

    public static boolean compare(T a, T b) {
        if (a.compareTo(b) > 0) {
            return true;
        }

        return false;
    }
}

Anyway, you should denote T extends Comparable<T> in the class declaration rather than in the method.

Upvotes: 1

Related Questions