简体   繁体   中英

How do you call a class that uses generic types in java?

I'm having trouble calling my SelectionSort class, which is listed below. I get an error "cannot access SelectionSort." I'm trying to see how long the SelectionSort class takes to sort a random array. Here is the SelectionSort class:

import java.lang.*;

public class SelectionSort {

public static <T extends Comparable<T>> void sort(T[] a) {
    selectionSort(a, a.length-1);
  }


  private static <T extends Comparable<T>> void selectionSort(T[] a, int n) {
    if (n < 0) return;
    int indMax = findMaxIndex(a, n);
    swap(a, n, indMax);
    selectionSort(a, n-1);
  }

  private static <T extends Comparable<T>> int findMaxIndex(T[] a, int n) {
    int indMax = 0;
    for (int i = 1; i <= n; i++) {
      if (a[indMax].compareTo(a[i]) < 0) {
        indMax = i;
      }
    }
    return indMax;
  }

  private static <T extends Comparable<T>> void swap(T[] a, int i, int j) {
    T tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
  }

  // Main function to test the code
  public static void main(String[] args) {

    // Make an array of Integer objects
    Integer[] a = new Integer[4];
    a[0] = new Integer(2);
    a[1] = new Integer(1);
    a[2] = new Integer(4);
    a[3] = new Integer(3);

    // Call the sorting method (type T will be instantiated to Integer)
    SelectionSort.sort(a);

    // Print the result
    for (int i = 0; i < a.length; i++)
      System.out.println(a[i].toString());
  }
}

Here is the part of the code where I try to call the class, I get the error in the second line

      long result;

      long startTime = System.currentTimeMillis();
      SelectionSort.sort(array,  100,  array.length-1);
      long endTime = System.currentTimeMillis();
      result = endTime-startTime; 

      System.out.println("The quick sort runtime is " + result + " miliseconds");
  }
}
SelectionSort.sort(array, 100, array.length-1);

This 3-argument method doesn't exist in the code you've shown us so presumably you can't call it.

int[] array = new int[size];

int is not an object so it can't extend Comparable . Arrays do not get auto-boxed so you must declare it as an Integer[] to pass it to a method that accepts a T[] where T extends Comparable<T> .

Integer[] a = new Integer[4];
SelectionSort.sort(a);

That part was OK and that is how you can call sort .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM