我是一名大二计算机科学专业的学生,目前正在学习Java编程语言,并且最近开始学习泛型。我有一个作业,要求使用给定的泛型排序算法对一个整数列表进行排序(不是原始类型int)。由于排序类使用了扩展Comparable的泛型,所以我认为只需将Integer数组传递给它们就没有问题了,但构建输出不断出现不兼容类型的错误。
相关代码如下:
主程序部分
我遇到的问题是在声明SelectionSort时,出现了一个错误,提示无法将构造函数应用于给定的类型。据我在这里和其他地方搜索得知,通常使用int时会遇到这种问题,但我不明白为什么Integer也不能工作。 如果您能就这个问题提供任何见解,我将非常感激,因为我还在逐渐理解泛型的概念。 非常感谢!
相关代码如下:
主程序部分
final int NUMITEMS = 100000;
Integer[] list = new Integer[NUMITEMS];
int dataSize = 0;
//method reads contents of a file into array and returns number of objects
System.out.println((dataSize = readDataFile(list)));
SelectionSort SS = new SelectionSort(list, dataSize);//problem is here
同时也提供了选择排序算法,期望使用不作修改。
class SelectionSort<T extends Comparable<? super T>> implements SortAlgorithm<T> {
public void sort ( T [ ] theArray, int size ) {
for (int last = size-1; last > 0 ; last--)
{
int largest = 0;
for (int scan = 1; scan <= last; scan++)
if (theArray[scan].compareTo(theArray[largest])>0)
largest = scan;
/** Swap the values */
T temp = theArray[largest];
theArray[largest] = theArray[last];
theArray[last] = temp;
}
} // method selectionSort
我遇到的问题是在声明SelectionSort时,出现了一个错误,提示无法将构造函数应用于给定的类型。据我在这里和其他地方搜索得知,通常使用int时会遇到这种问题,但我不明白为什么Integer也不能工作。 如果您能就这个问题提供任何见解,我将非常感激,因为我还在逐渐理解泛型的概念。 非常感谢!
错误:类SelectionSort<T>中的构造函数SelectionSort无法应用于给定类型; SelectionSort<Integer> SS = new SelectionSort<Integer> (list, dataSize); ^ 需要:无参数 找到:Integer[],int 原因:实际和形式参数列表长度不同 其中T是类型变量: T extends Comparable <? super T>在类SelectionSort中声明 1个错误
- JorCSortAlgorithm<T>
接口。 - Paul Bellora