首页 > 解决方案 > 无法将 int 添加到 ArrayLists 的 ArrayList

问题描述

我正在尝试制作基数排序算法,并且我有一个数组列表的数组列表。

基数排序根据数字的个位、十位、百位等位置的值将元素添加到“外部”数组列表中。每个“内部”数组列表对应一个数字位置 0、1、2、3...9。

变量“base”的值为 10,因为有 10 位数字 (0-9)

这是声明:

    ArrayList<ArrayList<Integer>> digits = new ArrayList<ArrayList<Integer>>(base); //arraylist that can hold 10 elements to sort elements according to digits 0-9

    for(int i=0; i <digits.size(); i++){

        digits.add(i, new ArrayList<Integer>()); //make an arraylist for each element inside the digits array list, this will hold the numbers that are being sorted
    }

但是,稍后当我尝试将整数添加到正确的“内部”数组列表中时,我无法将整数添加到类型为 ArrayList 的位置中。我也得到一个索引超出范围的错误。

while(!(lastDigit)) //if last digit has not been reached
    {
        lastDigit = true;

        for(int k=0; k < array.length; k++) //array contains the numbers we are sorting
        {
            number = k / digitPlace; //digitPlace starts off as 1 to first sort by one's place and is then later multiplied by 10 
            int index = number % base; //get digit from correct place

             digits.add(index, k);//line with the ERROR; add the element in the correct place (according to it's digit)

            if(number > 0 && lastDigit) 
            {
                lastDigit = false;
            }

        }

解决问题的方法是我将整数转换为 ArrayList 类型,但这意味着我会在内部数组列表中添加一个 Array List,这不是我想要的。我想将一个 int 添加到正确的“内部”ArrayList 中。

标签: javaarrayssortingarraylistradix-sort

解决方案


大小()的JavaDoc:

返回此列表中的元素数。(...)

ArrayList<ArrayList<Integer>> digits = new ArrayList<ArrayList<Integer>>(base);
for(int i=0; i < digits.size(); i++){
    digits.add(i, new ArrayList<Integer>());
}

您在 for 循环中引用列表的大小而不是容量

使用用于创建列表的基本变量而不是digits.size()


推荐阅读