我正在尝试制作基数排序算法,并且我有一个数组列表的数组列表。
基数排序根据数字的个位、十位、百位等位置的值将元素添加到“外部”数组列表。每个“内部”数组列表对应于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 中。
最佳答案
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/