删除和移动阵列中的对象



我一直在做一个项目,该项目从我创建的一个名为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被设计为使用插入、搜索、删除等方法来处理数据。创建delete方法时,我们会被指示搜索唯一的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

这里是searchArray:

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

其中index是当前正在评估的数组中的点。现在,是:

System.arraycopy(toolArray, 1, toolArray, 0, toolArray.length - 1);是否适合我的目的?我读了很多关于在数组中移动项目的不同方法的文章,这似乎是最简单的方法,但大多数人都将其与arrayList一起使用,我现在无法使用。非常感谢您的反馈。谢谢

否,arrayCopy不适用。请注意,您正在复制toolArray.length - 1元素,我不确定您如何不会遇到IndexOutOfBoundException s。

假设testArrayindexints,并且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

最新更新