java - 无法将 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 中。
解决方案
返回此列表中的元素数。(...)
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()
推荐阅读
- oracle-data-integrator - 在 ODI 文件到表加载 .bad 和 .error 文件未创建
- angular - 无法在离子数组中推送值
- nativescript - 下载时未连接或断开连接如何处理img src - Nativescript
- java - 可执行 Jar 找不到样式表
- bash - 在 bash_profile 别名命令中请求用户输入
- git - “git subtree add”因“文件取消链接”而失败
- javascript - YouTube 标题、分享、观看按钮已移除
- javascript - 使用 React 解析道具和函数
- python - Python日志记录 - 每次循环迭代的新日志文件
- c# - WebApi 请求中的取消