gpt4 book ai didi

Java - 基数排序 不兼容的类型?

转载 作者:行者123 更新时间:2023-12-01 18:36:39 25 4
gpt4 key购买 nike

对于我的类(class),我们必须为基数排序算法编写 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] + " ");
}
}

我标记了出现不兼容类型的行。我不想要如何修复它,但为什么类型不兼容。我真的不知道,我想了解为什么。感谢您的帮助。

最佳答案

您将存储桶声明为对象项列表,并且对象项无法转换为 int 值。所以它会在那里抛出编译错误。要修复该错误,您可以使用 @Elliott 提到的泛型,或重写代码,如下所示:

for (Object y: bucket[x]) {
list[z] = (Integer) y;
z++;
}

关于Java - 基数排序 不兼容的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21692810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com