简体   繁体   English

无法将int添加到ArrayLists的ArrayList中

[英]Unable to add int into an ArrayList of ArrayLists

I am trying to make a Radix Sort algorithm and I have an Array List of Array Lists. 我试图做一个基数排序算法,并且我有一个数组列表的数组列表。

Radix Sort adds elements to the "outer" array list depending on the value of a number's one's, ten's, hundred's, etc. place. Radix Sort根据数字的一个,十个,百个等位的值将元素添加到“外部”数组列表中。 Each "inner" array list corresponds to a digit place of 0, 1, 2, 3...9. 每个“内部”数组列表都对应一个数字位置0、1、2、3 ... 9。

The value of variable "base" is 10 as there are 10 digits (0-9) 变量“ base”的值为10,因为有10位数字(0-9)

Here is the declaration: 这是声明:

    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
    }

However, later when I try to add integers to the correct "inner" array list, I am unable to as I'm trying to add an integer into a place of type ArrayList. 但是,稍后当我尝试将整数添加到正确的“内部”数组列表时,由于尝试将整数添加到ArrayList类型的位置,因此无法执行操作。 I also get an index out of bound error. 我也得到了索引错误。

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;
            }

        }

The way to solve the problem is that I cast the integer to type ArrayList but that would mean that I would have added an Array List into the inner array list, which is not what I want. 解决问题的方法是将整数转换为ArrayList类型,但这意味着我将在内部数组列表中添加了一个Array List,这不是我想要的。 I want to add an int into the correct "inner" ArrayList. 我想将一个int添加到正确的“内部” ArrayList中。

JavaDoc of size(): size()的JavaDoc:

Returns the number of elements in this list. 返回此列表中的元素数。 (...) (...)

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

You are referencing the size of the List in the for-loop instead of the capacity ! 您在for循环中引用List的大小 ,而不是在容量中

Use the base variables used for creating the List instead of digits.size() 使用用于创建列表的基本变量代替digits.size()

digits.get(index).add(n);
其中n是要添加的输入数组中的数字。

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

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