java - 无法将 int 添加到 ArrayList 的 ArrayList 中

标签 java arrays sorting arraylist radix-sort

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

基数排序根据数字的个位、十位、百位等位置的值将元素添加到“外部”数组列表。每个“内部”数组列表对应于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 类型,但这意味着我将在内部数组列表中添加一个数组列表,这不是我想要的。我想将一个 int 添加到正确的“内部”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>());
}

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

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

关于java - 无法将 int 添加到 ArrayList 的 ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117624/

相关文章:

java - 如何在 Db2 的 SQL 查询中使用当前日期

c - 为什么这在 C(数组)中无效?

java - 如何删除字符串中的重复单词并以相同的顺序显示它们

python - 为 numpy 数组的行中的每个点找到最近的 k 个点

javascript - 数据表的显式排序

java - Maven3排除从父pom继承的不必要的依赖项进行分发?

java - 使用具有透明图像的 Graphics.copyArea

java - Java打印BufferedImage时出现空白页

php - DRY - 将一定数量的元素添加到数组末尾,直到它的计数达到特定的 int

Javascript 按姓氏对字符串数组进行排序