java - 删除和移动数组中的对象

标签 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,旨在使用插入、搜索、删除等方法来操作数据。创建删除方法时,系统指示我们搜索唯一 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 元素,我不确定您如何不会遇到 IndexOutOfBoundExceptions。

假设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例如。

关于java - 删除和移动数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26092354/

相关文章:

java - 将 fragment 布局纵向更改为横向

java - 如何增加catch block 中的值?

java - 在 Spring MVC 中实现视频

perl - 为什么所有这些访问数组的方法都有效?

java - 由元组及其值组成的记录的高效数据结构

java - 在 Java 中翻转硬币

ios - 未保存 PDF 注释

ios - 展平具有重复值的字典数组 Swift 3.0

java - 通过构造函数从用户获取输入时出现意外结果

c++ - 如何找到数组的长度?