繁体   English   中英

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

[英]Java - Radix Sort Incompatible types?

对于我的班级,我们必须为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] + " ");
    }    
}

我在获取不兼容类型的地方标记了这一行。 我不想只是解决它,而是为什么类型不兼容。 我真的不知道,我想知道为什么。 谢谢你的帮助。

您已将bucket声明为Object项目列表,并且Object项目无法转换为int值。 因此它在那里引发了编译错误。 要解决该错误,您可以使用@Elliott所述的泛型,或在此处重写代码,如下所示:

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

为了使用泛型,您将需要输入ArrayList ,即

ArrayList<Integer>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM