0

I am working on a sorting algorithm class and a main class to test the Sorting Algorithms. Whenever I try to call a method from the sorting algorithm class in the main class, I get an error similar to this one:

The method quickSortRandom(T[], int) in the type SortAlgorithms is not applicable for the arguments (int[], int)

I am attempting to input an array of integers into a method that accepts Type T[], and I do not understand why that doesn't work or how to fix it. Here is the main method:

public static void main(String args[]) {
        int arr[] = {10, 7, 8, 9, 1, 5};
        int n = arr.length;
        
        SortAlgorithms s = new SortAlgorithms();
        s.quickSortRandom(arr,arr.length); }

And here is the quickSortRandom method in the sorting algorithms class:

public static <T extends Comparable<? super T>>
       void quickSortRandom(T[] array, int n)
    {
        quickSortRandom(array, 0, n-1);
    } // end quickSortRandom
Mureinik
  • 297,002
  • 52
  • 306
  • 350

2 Answers2

2

The method currently accepts any array of Comparables. However, unfortunately, primitives (such as ints) aren't comparables, and you'll need to use the wrapper class, java.lang.Integer instead:

Integer[] arr = {10, 7, 8, 9, 1, 5};
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

The reason, why this not works is, that int in Java is a primitive data type. You need a referential data typed (Something inheriting Object), for example Integer (the wrapper class for ints). Generic Types T may only be references, so you must wrap you ints into Integers, which automatically happens, as soon as you change the data Type of int arr[] to Integer arr[].

And of course, as mentioned by Mureinik: T must be a Comparable, which int isn't and can't be.

edean
  • 498
  • 3
  • 11