问题描述
我正在尝试对数组中的数据进行排序。
我已经创建了一个对数据进行排序的方法,但由于某种原因,我无法在 main
方法中正确调用此方法。
有些东西不起作用。 driver
类必须调用该方法并发送正确的参数。我试图这样做,但它不起作用。参数有问题。该程序应该接收数据并对其进行排序。
public class Kennel
{
public static <T extends Comparable<T>>
void selSort(T[] doggy)
{
//local variables
T temp;
Dog doggy[ ] = new Dog [MAX_DOGS]; //dog array
int outerLoop; // Outer loop counter
int innerLoop; //Inner loop counter
int location; //Location of smallest value
int n = doggy.length; //number of items in the array
/***************************************************/
for (outerLoop = 0; outerLoop < n - 1; outerLoop++)
{
//
location = outerLoop;
//
for (innerLoop = outerLoop + 1; innerLoop < n; innerLoop++)
{
if (doggy[location].compareto((doggy[innerLoop])) > 0)
{
location = innerLoop;
}//end IF
}//end FOR
>swap the value of the old smallest with the value of the new smallest<
T iSwap = doggy[location];
doggy[location] = doggy[outerLoop];
doggy[outerLoop] = iSwap;
}//end FOR
}//end selSort
主要方法
public static void main(String args[])
{
mid = new Kennel();
mid.selSort(mid.doggy);
}
117: error: method selSort in class Kennel cannot be applied to given types;
mid.selSort(mid.doggy);
^
required: T[]
found: Dog[]
reason: inferred type does not conform to upper bound(s)
inferred: Dog
upper bound(s): Comparable<Dog>
where T is a type-variable:
T extends Comparable<T> declared in method <T>selSort(T[])
1 error
不知道如何解决这个问题。
解决方法
几点。
- 您的 Dog 类应该类似于
class Dog implements Comparable<Dog> {
// fields,constructor,etc here
public int compareTo(Dog dog) {
...
return val; // where val is an int depending on result of comparison
}
// other methods here.
}
-
在 sort 方法中使用
Dog array
并接受一个作为参数是没有意义的。 Dog 数组将就地排序,因此不需要内部的狗数组。 -
您需要使用
Dog array
填充Dog objects
并将该数组传递给 sort 方法。