繁体   English   中英

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

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

我在调用我的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");
  }
}
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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