[英]How do you call a class that uses generic types in java?
I'm having trouble calling my SelectionSort class, which is listed below. 我在调用我的SelectionSort类时遇到问题,如下所示。 I get an error "cannot access SelectionSort."
我收到错误“无法访问SelectionSort”。 I'm trying to see how long the SelectionSort class takes to sort a random array.
我试图看看SelectionSort类对随机数组进行排序需要多长时间。 Here is the SelectionSort class:
这是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());
}
}
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. 这个3参数方法在您向我们展示的代码中不存在,因此可能您无法调用它。
int[] array = new int[size];
int
is not an object so it can't extend Comparable
. int
不是一个对象,所以它不能扩展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[]
以将其传递给接受T[]
的方法,其中T extends Comparable<T>
。
Integer[] a = new Integer[4];
SelectionSort.sort(a);
That part was OK and that is how you can call sort
. 那部分还可以,你可以调用
sort
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.