Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array of Integers with generics (Java)

I'm a second year computer science student currently working in Java and we recently started generics. I have an assignment where I've been given a list of sorting algorithms that use generics and am tasked with using them to sort a list of Integers (not primitive ints). As the sort classes use generics that extend Comparable I thought there would be no problems simply handing them the Integer array but the build output keeps coming up with incompatible types.

The relevant code is below;

portion of Main program

final int NUMITEMS = 100000;
Integer[] list = new Integer[NUMITEMS];
int dataSize = 0;

//method reads contents of a file into array and returns number of objects
System.out.println((dataSize = readDataFile(list)));

SelectionSort SS = new SelectionSort(list, dataSize);//problem is here

And the SelectionSort algorithm which is provided and expected to be used as-is

class SelectionSort<T extends Comparable<? super T>> implements SortAlgorithm<T>  {

public void  sort ( T [ ] theArray,   int size ) {

  for (int last = size-1; last > 0 ; last--)
  {
     int largest = 0;
     for (int scan = 1; scan <= last; scan++)
        if (theArray[scan].compareTo(theArray[largest])>0)
           largest = scan;

     /** Swap the values */
     T temp = theArray[largest];
     theArray[largest] = theArray[last];
     theArray[last] = temp;
  }
} // method selectionSort

The problem I'm having is in declaring SelectionSort, which returns an error that the constructor cannot be applied to the given type. From what I've read in my searches here and elsewhere this kind of problem is usually encountered when using ints, but I don't understand why it isn't working with Integers. Any insight on the problem would be greatly appreciated as I'm still coming to terms with the concept of generics. Many thanks in advance!

like image 296
JorC Avatar asked Nov 05 '12 22:11

JorC


1 Answers

This should fix the problem:

SelectionSort<Integer> ss = new SelectionSort<Integer>();
ss.sort(list, dataSize);

You were trying to pass arguments into a constructor that didn't exist, when you want to pass them into the sort method instead.

Here I'm using the default (no-arg) constructor to instantiate a new SelectionSort<Integer>, assigning it to a variable ss, then calling sort on that instance with the arguments.

Also note that if you just need the instance to call sort, you can skip the assignment:

new SelectionSort<Integer>().sort(list, dataSize);
like image 140
Paul Bellora Avatar answered Nov 11 '22 23:11

Paul Bellora