java - 索引超出范围,从 am 数组中删除项目
问题描述
我正在尝试添加通过方法调用从数组中删除项目的功能,但遇到了标题中发布的问题。
以下是说明:
为 ArrayIntList 类编写一个名为 remove 的新方法,该方法采用整数索引并删除给定索引处的值,将后续值向左移动。例如,如果一个名为 list 的变量存储以下值:
[3, 19, 42, 7, -3, 4]
进行此方法调用后:
“list.remove(1);” 将从数组中删除 3 (这不是特定于数组的第一个值
我试图实现这样做:
public void remove(int index) {
int target = index;
int[] elementDataCopy = new int[size];
size = elementData.length;
if (index < 0 || index >= size) {
throw new IllegalArgumentException("invalid index");
}
//loop through each value until the index given is == to loop value
//create a copy of elementData where length is one less and value at
//index given is not present
//each time something is removed, the tracked values decrease by one
size--;
for(int i = 0; i < elementData.length + 2; i++){
if (elementData[i] == target){
continue;
}else{
elementDataCopy[i] = elementData[i];
}
}
}
``
but get this error:
失败:索引 12 超出长度 12 的范围
with the numbers differing depending on what input is.
note that elementData is an array of ints and index is an int that is pointing at a point in said array
all help is appreciated, pretty sure this is something basic
解决方案
像这样试试。最大的错误是i
同时使用源索引和目标索引。使用单独的(k
此处)作为目的地。仅在制作副本时增加目标索引。完成后,将 elementDataCopy 重新分配给 elementData。
int k = 0;
for(int i = 0; i < elementData.length; i++) {
if (i == index) { // skip the one to "delete"
continue;
}
elementDataCopy[k++] = elementData[i];
}
elementData = elementDataCopy;
推荐阅读
- c# - OpenTK (OpenGL) Lighting:为什么纹理只在对象的内部可见?
- javascript - 如何同时流式传输文本和视频?
- javascript - 使用递归对数组中的元素求和,即使它们是字符串
- flutter - 为什么在 initState() 之前调用 Statefull 小部件的 build() 函数?
- javascript - Vue中的外部JS文件
- python - py2app 不包括 Python 内置 .app
- javascript - 变量没有传递给 Pug
- python - 在 GCP 上制作可扩展的 postgres 源机器学习管道
- tensorflow - 多个模型运行的 val 准确度差异很大的原因是什么?
- mysql - 我无法在 ubuntu 上更改 mysql root 密码