你如何调用在java中使用泛型类型的类?

时间:2014-03-15 23:15:56

标签: java generics

我无法调用我的SelectionSort类,如下所示。我收到错误“无法访问SelectionSort”。我试图看看SelectionSort类对随机数组进行排序需要多长时间。这是SelectionSort类:

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());
  }
}

以下是我尝试调用该类的代码部分,我在第二行中收到错误

      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");
  }
}

1 个答案:

答案 0 :(得分:2)

SelectionSort.sort(array, 100, array.length-1);

这种3参数方法并不存在于您向我们展示的代码中,因此您可能无法调用它。

int[] array = new int[size];

int不是对象,因此无法扩展Comparable。数组不会自动装箱,因此您必须将其声明为Integer[],以便将其传递给接受T[] T extends Comparable<T>的方法。

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

那部分没问题,你可以拨打sort