繁体   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