0

I am new to Java and facing a problem in declaring generic array as static. I need your help to solve and understand what is going wrong.

public class ThreadedSorter<E>  {

    private static int number_of_threads = 2;

    private static E[] array, aux;    

    ....

    public static <E> E[] mergeSort(E[] unsortarray) {
        array = unsortarray;
        .....
        return array;
    }

    private static void mergeSortHelper(int low, int hi) {
        if(low==hi) return;
        int mid = (low+hi) >> 1;
        mergeSortHelper(low,mid);
        mergeSortHelper(mid+1, hi);
        merge(low,mid+1,hi);
    }

    private static void merge(int low, int hi, int upperBound) {

        .....

        while(low <=mid && hi <= upperBound)
            if(array[low] <= array[hi])
                aux[j++] = array[low++];
        ........
    }


endclass

I am facing issue for following declaration - saying non static type variable can not be referenced from a static context.

"private static E[] array, aux;"

Can you please tell me where I am missing.

Regards, Pratik

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Pratik
  • 1
  • Simply do not use arrays, expecially when dealing with generics. Use collections! – Seelenvirtuose Nov 15 '14 at 07:30
  • Note that your `mergeSort` method should not have a type parameter `` - note that that is a different type parameter that is hiding the type parameter `E` from the class. – Jesper Nov 15 '14 at 07:48

2 Answers2

1

What you are trying to do simply can't be done. There are no generic static members.

So normally you would pass these arrays to your other methods.

public static <E> E[] mergeSort(E[] unsortarray) {
    ...
}

private static <E> void mergeSortHelper(
    E[] arr, E[] aux, int low, int hi
) {
    ...
}

private static <E> void merge(
    E[] arr, E[] aux, int low, int hi, int upperBound
) {
    ...
}

Keeping this helper data as static members is not really a good idea anyway because it means your methods cannot be called concurrently.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
1

First you need to study what the static modifier is, since it is the source of the error you are asking for. https://stackoverflow.com/a/413904/3657704

I dont see why would you use static modifiers everywhere in your code, of course in a more advanced talk i would say that you try to accomplish something having a lot of static fields and methods in a class named "ThreadedSorter".

Does it makes sense to you have a class method calling an instance variable? it probably wont find it since the classloader loads static fields and methods even were no instances of your object exist, yet.

And of course radiodef answer is right, too.

Community
  • 1
  • 1
Ringo
  • 850
  • 9
  • 24