简体   繁体   中英

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. Each "inner" array list corresponds to a digit place of 0, 1, 2, 3...9.

The value of variable "base" is 10 as there are 10 digits (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. 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. I want to add an int into the correct "inner" ArrayList.

JavaDoc of size():

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 !

Use the base variables used for creating the List instead of digits.size()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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