簡體   English   中英

Java - 從數組中刪除對象

[英]Java - removing object from Array

我需要創建一個方法來從對象數組中刪除一個元素,而不是將它變成一個 ArrayList。

這是我的對象的構造函數:

public Person(String name1, String telno1)
{
    name = name1;
    telno = telno1;
} 

還有我的數組:

int capacity = 100;
private Person[] thePhonebook = new Person[capacity]; 

我有一個用於刪除方法的外殼:

public String removeEntry(String name)
{
    //name is name of the person to be removed (dont worry about duplicate names)
    //returns the telephone number of removed entry
}

我不知道如何刪除數組中的元素(我不想只是將值設置為 null)

我確實想過創建一個新數組並復制要刪除的元素兩側的部分以形成一個新數組,但我不確定如何實現。

我還有一個 find 方法,可用於在數組中查找人名,如果有幫助的話:

private int find(String name)
{
    String name1 = name;

    int i = 0;
    int elementNo = 0;
    int found = 0;

    while(i < size)
    {
        if(thePhonebook[i].getName().equals(name1))
        {
            elementNo = i;
            found = 1;
            break;
        }
    }

    if(found == 1)
    {
        return dirNo;
    }
    else
    {
        dirNo = -1;
        return dirNo;
    }
} 

謝謝你的時間。

要做到這一點是獲取數組中的最后一個索引,然后將其傳遞給剛剛刪除的索引並刪除最后一個數組.. 如果該數組是最后一個,請不要刪除它。

for(int i = 0; i < thePhonebook .length; i++)
{
    if(thePhonebook[i].getName().equals(string))
    {
            if(i == thePhonebook .length - 1)
              thePhonebook[i] = null;
            else
            {
              thePhonebook[i] = null;
              thePhonebook[i] = thePhonebook[thePhonebook .length - 1];
               thePhonebook[thePhonebook .length - 1] = null;
            }
     }
}

您不能直接從 Java 中的數組中刪除元素。 你兩個選擇:

A. 如果必須保留數組中元素的順序:從要刪除的索引開始,將每個元素“向下”移動一個索引(向索引 0),如下所示:

    public String removeEntry(String name)
    {
        String result = null;
        int index = find(name);
        if (index >= 0)
        {
            result = thePhonebook[index].telno;
            for (int i = index + 1; i < thePhonebook.length; ++i)
            {
                thePhonebook[i - 1] = thePhonebook[i];
                if (thePhonebook[i] == null)
                {
                    break;
                }
            }
            thePhonebook[thePhonebook.length - 1] = null;
        }
        return result;
    }

在上面的實現中,數組中的null值表示列表的結尾。

B. 如果數組中元素的順序無關緊要:將要刪除的元素與列表的最后一個元素交換。 請注意,要執行此操作,您需要為列表維護一個長度值,即下面代碼中的值thePhonebookLength

    public String removeEntry(String name)
    {
        String result = null;
        int index = find(name);
        if (index >= 0)
        {
            result = thePhonebook[index].telno;
            thePhonebook[index] = thePhonebook[thePhonebookLength - 1];
            thePhonebook[--thePhonebookLength] = null;
        }
        return result;
    }

這兩種解決方案的一個好處是可以就地修改數組,而不使用分配。

提供了這些可能性之后,我建議使用集合更適合您的目的——例如List子類之一,或者如果按名稱查找很常見,甚至可能是Map

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM