Java: Can I create Generic-typed static classes? -
i'm working on quicksort algorithm in java, , i'm required use arrays.
right now, want make algorithm support sorting array of comparables.
i've looked around, of discussion , tutorials around generics pretty confusing. put, i'm not sure how make work. i've confirmed quicksort works integers, strings, etc, need make work comparables. ide telling me "cannot make reference non-static type t". i'm not sure means.
public class quicksort<t extends comparable<t>> { public static void sort(t[] a) { quicksortrecursive(a, 0, a.length-1); } public static void quicksortrecursive(t[] a, int p, int r) { if( p < r ) { int q = partition(a, p, r); quicksortrecursive(a, p, q-1); quicksortrecursive(a, q+1, r); } } public static int partition(t[] a, int p, int r) { string x = a[r]; int = p - 1; for(int j = p; j < r; j++) { if(a[j].compareto(x) <= 0) { = + 1; //swap a[i] a[j] t tmp = a[i]; a[i] = a[j]; a[j] = tmp; } } //swap a[i + 1] a[r] t tmp2 = a[i + 1]; a[i + 1] = a[r]; a[r] = tmp2; return + 1; } }
in nutshell, doing wrong here?
oh ... ...
when designing generic class like
class quicksort<t extends comparable<t>> { ... }
that means instances of class can (and should) parameterized concrete type parameters. example can declare
quicksort<string> sorter = new quicksort<>();
static methods not belong instances, these methods have no clue meaning of type paramater t
. make static methods generic themselves:
static <t> void sort(t[] a) { ... } static <t> void quicksortrecursive(t[] a, int p, int r) { ... } static <t> int partition(t[] a, int p, int r) { ... }
but leads other errors. example, have following line in method partition
:
string x = a[r];
as parameter a
type t[]
, compiler not allow assignment of array's element string
typed variable (t
anything). if know, these strings, why not declare
static int partition(string[] a, int p, int r) { ... }
no need generics here.
additionally, oop objects (aka instances) , not static methods more procedural design. remove static keyword methods , change above mentioned problematic line
t x = a[r];
then fine , can use class following:
quicksort<string> sorter = new quicksort<>(); string[] strings = somestrings(); sorter.sort(strings);
as side note: java code conventions method , variable names should start lower letters, better name methods sort
, quicksortrecursive
, , partition
.
Comments
Post a Comment