1

配列内の 1 つのオブジェクトを検索して削除するこのコードがあります。他のいくつかのメソッドがこの配列で機能するため、その位置に問題があります (そして、毎回 NullPointerException が返されます)。私の方法は次のようになります。

public void deleteHotel(String hotelName) {
    for (int i = 0; i < this.hoteis.length; i++) {
        if (this.hoteis[i].getName().equalsIgnoreCase(nomeHotel)) { //searches the array, looking for the object that has the inputted name
            this.hoteis[i] = null; //makes that object null
            if (this.hoteis.length > 1 && this.hoteis[this.hoteis.length - 1] != null) { //for arrays with lenghts bigger than 1 (since there's no problem with an array with one position)
                for (int x = i; x < this.hoteis.length; x++) {
                    this.hoteis[x] = this.hoteis[x + 1]; //makes that null position point to the next position that has an object, and then that position points to the object in the next position and so on
                }
                this.hoteis[this.hoteis.length - 1] = null; //since the last to positions will be the same, make that last one null
                Hotel[] hoteisTemp = new Hotel[this.hoteis.length - 1];
                for(int x = 0; x < this.hoteis.length - 1; x++){ //create a new array with one less position, and then copy the objects on the old array into the new array, then point the old array to the new array
                    hoteisTemp[x] = this.hoteis[x];
                }
                this.hoteis = hoteisTemp;
            }
            i = this.hoteis.length;
        }
    }

}

他のメソッド (たとえば、各オブジェクトの実装された toString() を返すメソッド) を使用すると、NullPointerException が発生します。コードのエラーを特定できますか? とても有難い...

4

5 に答える 5

1

コードを書き直すことを検討してください

List result = new ArrayList();
for (int i = 0; i < this.hoteis.length; i++) {
    if (!this.hoteis[i].getName().equalsIgnoreCase(nomeHotel)) {
        result.add(this.hoteis[i]);
    }
}
return result.toArray();
于 2013-07-17T21:18:35.993 に答える
0

配列要素を左にシフトしているポイント

for (int x = i; x < this.hoteis.length; x++) {
    this.hoteis[x] = this.hoteis[x + 1];
}

ループ条件はx < this.hoteis.length - 1、最後の反復x = this.hoteis.length - 1でインデックス値this.hoteis[x + 1]NullPointerException.

于 2013-07-17T21:19:22.773 に答える