删除和移动数组中的对象

时间:2014-09-29 04:01:11

标签: java arrays

我一直致力于一个项目,该项目从我创建的类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,旨在使用insert,search,delete等方法操作数据。创建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。任何反馈都非常感谢。谢谢!

1 个答案:

答案 0 :(得分:1)

不,arrayCopy不合适。请注意,您正在复制toolArray.length - 1个元素,我不确定您是如何遇到IndexOutOfBoundException的。

假设testArrayindexint,而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

相关问题