对于我的课,我们必须编写Radix Sort算法的Java代码。我理解算法,我认为我有解决方案,但我的代码中出现了不兼容的类型错误,我不明白为什么。
import java.util.*;
public class RadixSort {
public static void radixSort(int[] list) {
// will be passed to getKey to decide what to divide the number by before %10
int div = 1;
// repeat once for the max number of digits of the numbers
for (int i = 0; i < 3; i++) {
ArrayList bucket[] = new ArrayList[19];
// distribute the elements from the list to the buckets
for (int j = 0; j < list.length-1; j++) {
int key = getKey(list[j], div);
// add 9 so that if key is negative, it will now be 0 or positive so an out of bounds exception isn't thrown
// so bucket[0] means the key was -9, and bucket[18] means the key was 9
if (bucket[key+9] == null)
bucket[key+9] = new ArrayList();
bucket[key+9].add(list[j]);
}
// move the elements from the buckets back to list
int z = 0;
for (int x = 0; x < 19; x++) {
if (bucket[x] != null) {
for (int y: bucket[x]) { // incompatible types???
list[z] = y;
z++;
}
}
}
// multiply div by 10 for the next run-through
div = div*10;
}
}
public static int getKey(int i, int j) {
return (i/j) % 10;
}
// test method
public static void main(String[] args) {
int[] list = {922, 243, 409, 885, 96, 21, -342, 119, 540, 12, -732, 8, -3, 2};
radixSort(list);
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
}
}
我标记了我遇到不兼容类型的行。我不想只是如何解决它,但为什么类型不兼容。我真的不知道,我想明白为什么。谢谢你的帮助。
答案 0 :(得分:3)
您将存储桶声明为对象项列表,并且无法将对象项强制转换为int值。所以它在那里抛出一个编译错误。 要修复错误,您可以使用Generics作为@Elliott提到,或者重写代码如下:
for (Object y: bucket[x]) {
list[z] = (Integer) y;
z++;
}
答案 1 :(得分:1)
要使用Generics,您需要输入ArrayList
,即
ArrayList<Integer>