在数组中查找要替换为null的项

时间:2018-04-15 12:11:50

标签: java

我使用数组来按字母顺序存储属性详细信息。我知道我不能从数组中删除任何内容,但我想知道如何找到一个指定的属性,然后将所有其他的属性移到索引中,并将最后一个替换为null,这样我就没有重复了结束。我的代码似乎永远不会出现在循环中。

public void removeProperty(String reference) {
    int index;
    Boolean found = false;
    for (index = 0; index < this.propertyList.length; index++) {
        if (this.propertyList[index].getReference().equalsIgnoreCase(reference)) {
            this.propertyList[index] = this.propertyList[index + 1];
            found = true;
        } else {
            index++;
        }

        if (found = true){
            while (index < this.propertyList.length) {
                this.propertyList[index] = this.propertyList[index + 1];
            }
            this.propertyList[this.propertyListSize - 1] = null;
            this.propertyListSize--;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这是一个不使用布尔标志的解决方案。其他已解决的错误包括:

1)index循环中for的增加

2)while循环直到最后一项。这将导致ArrayIndexOutOfBounds除外。循环应该一直持续到最后一个项目。

public void removeProperty(String reference) {
    int index;
    // loop until reference found or end of array
    for (index = 0;
         index < this.propertyList.length &&
            this.propertyList[index].getReference().equalsIgnoreCase(reference) == false;
         index++);

    // if we didnt reach end of array - then we found refernce
    if (index < this.propertyList.length) {
        // loop until item before last
        while (index < this.propertyList.length-1) {
            this.propertyList[index] = this.propertyList[index + 1];
            index++;
        }
        // nullify last item
        this.propertyList[this.propertyList.length-1] = null;
        this.propertyListSize--;
    }
}

答案 1 :(得分:-1)

我知道这不能回答你的大多数问题,但你可以使用apache commons ArrayUtils从数组中删除一个项目。 Here's链接。