previous | start

Sorting Arrays of any Type

Individual methods in a non-generic class can be generic, but will need to declare the generic type variable.

For example, here is a Bubble class with a static generic sort method:

public class Bubble implements Sort {

   public <E extends Comparable<E>> void sort(E[] a)
   {
      for(int len = a.length; len > 1; len--) {
         for(int i = 1; i < len; i++) {
            if ( less( a[i], a[i - 1])) {
                    swap(a, i, i - 1);
            }
         }
      }
   }
}


previous | start