我一直在开发一个项目,该项目从我创建的名为 ToolItem
的类创建对象数组(硬件工具)。它看起来是这样的:
private ToolItem[] toolArray = new ToolItem[10];
for (int i = 0; i < toolArray.length; i++)
{
toolArray[i] = new ToolItem();
System.out.println(toolArray[i]);
}
我当前正在开发的类名为ToolWarehouse
,旨在使用插入、搜索、删除等方法来操作数据。创建删除方法时,系统指示我们搜索唯一 ID,如果匹配,则将所有数据成员设置为 0。之后,系统指示我们删除数组的成员并将所有内容向左移动。关于如何移动数组的说明从未被教导/提及,所以我做了一些挖掘并想出了这个:
public void delete(int ID)
{
testArray = searchArray(ID); //method used to search array for specified ID
for (index = 0; index < toolArray.length; index++)
{
if (testArray == index)
{
toolArray[index].setQuality(0);
toolArray[index].setToolName("");
toolArray[index].setID(0);
toolArray[index].setNumberInStock(0);
toolArray[index].setPrice(0.0);
System.arraycopy(toolArray, 1, toolArray, 0, toolArray.length - 1);
numberOfItems--;
}
}
}//end delete
这是搜索数组:
public int searchArray(int id)
{
for (index = 0; index < toolArray.length; index++)
{
if (toolArray[index].getToolID() == id)
{
System.out.println("ID found at location " + index);
return index;
}
}
return -1;
}//end searchArray
其中索引是当前正在评估的数组中的位置。现在,是:
System.arraycopy(toolArray, 1, toolArray, 0, toolArray.length - 1);
适合我的目的吗?我已经阅读了很多有关在数组中移动项目的不同方法的文章,这似乎是最简单的方法,但大多数人都将其与 arrayList 一起使用,而我现在无法使用它。非常感谢任何反馈。谢谢!
最佳答案
不,arrayCopy
不适合。请注意,您正在复制 toolArray.length - 1
元素,我不确定您如何不会遇到 IndexOutOfBoundException
s。
假设testArray
和index
是int
,并且toolArray
是某种对象类型的数组,我认为你可以这样做:
public void delete(int ID)
{
testArray = searchArray(ID); //method used to search array for specified ID
// do things on the element that is returned from searchArray().
toolArray[testArray].setQuality(0);
toolArray[testArray].setToolName("");
toolArray[testArray].setID(0);
toolArray[testArray].setNumberInStock(0);
toolArray[testArray].setPrice(0.0);
// shift the rest.
for (index = testArray + 1; index < toolArray.length; index++)
{
toolArray[index - 1] = toolArray[index];
}
// now toolArray[toolArray.length - 2] and toolArray[toolArray.length - 1]
//points to the same object. Let's empty the last cell of the array
toolArray[toolArray.length - 1] = null;
}//end delete
请注意,每次移动时,数组末尾都会出现一个 null
单元格。我认为你应该考虑使用可以增长或缩小的集合,ArrayList
例如。
关于java - 删除和移动数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26092354/