Home > Software design >  Generic Comperable Type Java - Error if I set the function to static
Generic Comperable Type Java - Error if I set the function to static

Time:01-08

Good evening,

something quirky is going on with Java. I'll be the first to admit that I suck at Java, but I really can't wrap my head around this one, maybe someone can help.

I'm trying to make a class to execute GnomeSort (some niche sorting method, just to practice with Java).

Here's what I've build...

package sorting;

import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Arrays;

import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;

public class GnomeSort<T extends Comparable<? super T>> {

    public static void main(String[] args) {}

    public static T[] gnomeSort(T[] arrayToSort) {
        for (int i = 0; i < arrayToSort.length; i  ) {
            T current = arrayToSort[i];
            T next = arrayToSort[i   1];

            if (current.compareTo(next) > 0) {
                current = arrayToSort[i   1];
                next = arrayToSort[i];
            }
        }
        return arrayToSort;
    }

    static ArrayList<Character> sample = new ArrayList<Character>(
            Arrays.asList('t', 'f', 'a', 'b', 'u', 'd', 'g', 'c'));


    @Test
    public void testGnomeSort() {
        Character[] processed = {'t', 'f', 'a', 'b', 'u', 'd', 'g', 'c'};
        Character[] ordered = {'a', 'b', 'c', 'd', 'f', 'g', 't', 'u'};
        GnomeSort.gnomeSort(processed);
        assertArrayEquals(processed, ordered);
    }

}

the gnomeSort method, for some reason is giving the error:

'sorting.GnomeSort.this' cannot be referenced from a static context

If I remove it, the error goes away, but of course at that point the whole method would be completely useless, since as you can see I'm trying to execute the sort, and return the array.

I honestly don't have anything else to tell you. If you need some further clarification or explenation, please just let me know. I will be back immediately.

Thank you in advance for any help :)

CodePudding user response:

The type T exists at the bound instance level, you can introduce another generic bound for the static method. Also, you want to iterate to arrayToSort.length - 1 (since you use i 1 to get next in the loop body). And your swap is backward. Like,

public static <E extends Comparable<? super E>> E[] gnomeSort(E[] arrayToSort) {
    for (int i = 0; i < arrayToSort.length - 1; i  ) {
        E current = arrayToSort[i];
        E next = arrayToSort[i   1];

        if (current.compareTo(next) > 0) {
            arrayToSort[i   1] = current;
            arrayToSort[i] = next;
        }
    }
    return arrayToSort;
}

Looking at the rest of your code it seems like you don't need T (or for GnomeSort to be generic at the class level).

  • Related