Home > other >  How can multiple static methods use the same generic type?
How can multiple static methods use the same generic type?

Time:01-01

While learning from Algorithms (4th edition) (by Robert Sedgewick; Kevin Wayne), I am trying to recreate their codes. They have raw uses of parametrized constructors (generics) which I assume might be because 2011 Java code is different from today's Java code. Here is an example:

private static boolean less(Comparable v, Comparable w) {
   return (v.compareTo(w) < 0);
}

This works in Java 11/18. But the problem is my IDE highlights this as "raw use of parameterized constructor". According to what I read, I should not be doing this.

But there seems to be no solution where I can both: keep the method static and use generic types for Comparable.

Making the class generic doesn't really help, as the methods then cannot use the generic type of the class

enter image description here Error message: 'SelectionSort.this' cannot be referenced from a static context

But adding the generics to individual methods also doesn't work as other methods that I call dont know that their type <T> and the calling method's <T> are the same. Here is my attempt:

public class SelectionSort {
    public static <T> void sort (Comparable<T>[] array) {
        for (int i = 0; i < array.length; i  ) {
            int min = i;
            for (int j = i 1; j < array.length; j  ) {
                if (less(array[j],array[min]))
                    min = j;
            }
            exch(array, i, min);
        }
    }

    private static <T extends Comparable<T>> boolean less(Comparable<T> v, Comparable<T> w) {
        return (v.compareTo(w) < 0);
    }

    private static <T extends Comparable<T>> void exch(Comparable<T>[] a, int i, int j) {
        Comparable<T> swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }
}

enter image description here Error message: no instance of type variable T exist so that T conforms to Comparable

As you can see Java doesn't know both T's are the same. I feel there is a very simple solution here which I just am not getting.

CodePudding user response:

Comparable.compareTo() expects a T, not just a Comparable<T>. So the second method signature has to be

private static <T extends Comparable<T>> boolean less(T v, T w) {

And in order to call it, the first method also needs an array of T:

public static <T extends Comparable<T>> void sort (T[] array) {
  • Related