假设我有一个包含10个元素的数组。我程序的另一部分确定我必须删除索引4处的项目。
删除项目和缩短数组的最有效方法是什么?
我编写了以下方法,但它似乎无法正常工作。我错过了什么,例如,如果要删除的索引是0?通过发送数组和要删除的索引来调用该方法。
我意识到有阵列列表和其他类型的列表。然而,这是编程课程的作业,必须使用ARRAY。
//Removes the index from the array and returns the array.
NumberTile[] removeAndTrim(NumberTile[] array, int index){
NumberTile[] save = array;
array = new NumberTile[save.length-1];
for (int i=0; i<index; i++){
array[i]=save[i];
}//end for loop
for (int j=index; j<save.length-1; j++){
array[j]=save[(j+1)];
}
return array;
}//end removeAndTrim
答案 0 :(得分:3)
假设这是一个不允许使用库,arraylist或System.arraycopy等实用程序类的练习,那么您的方法是最有效的。推理:
作为一个样式点,你应该调用新数组“结果”或类似的东西,避免摆弄试图保存数组。这没有意义 - 你无法改变输入参数。
请注意,您的功能需要按如下方式使用:
NumberTile[] newArray=removeAndTrim(oldArray,index);
答案 1 :(得分:2)
public NumberTile[] removeAndTrim(NumberTile[] a, int index){
NumberTile[] result = new NumberTile[a.length-1];
for (int i = 0; i < result.length; i++){
result[i] = a[((i < index) ? i : i + 1)];
}
return result;
}
最有效的方法是一次循环/遍历和一次阵列创建 (不使用arraycopy)。
注意:这根本不会改变参数数组的值,只返回一个新值。
答案 2 :(得分:0)
NumberTile[] removeAndTrim(NumberTile[] array, int removeIndex) {
NumberTile[] newArray = new NumberTile[array.length - 1];
for (int i = 0; i < removeIndex; i++) {
newArray[i] = array[i];
}
for (int i = removeIndex + 1; i < array.length - 1; i++) {
newArray[i] = array[i + 1];
}
return newArray;
}