【发布时间】:2013-07-17 21:09:47
【问题描述】:
我有这段代码可以搜索数组中的一个对象并将其删除。我的位置有问题,因为其他一些方法可以使用这个数组(它每次都会给我一个 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()s 的方法)时,它会给我一个 NullPointerException。你们能找出代码中的错误吗?非常感谢...
【问题讨论】:
-
当您使用
ArrayList时,您确实意识到此功能开箱即用,对吧?所有这些代码都简化为:list.remove("name") -
如果我没有,我不会问这个问题,我会寻找它。不过,我想用数组试试这个。
-
不重新排列所有的数组,为什么不把数组的最后一个对象移动到已删除酒店的位置呢?然后你可以从头到尾进行处理 ||空指针。这将需要一个变量来存储最后一个对象的位置。或者它可以是一个简单的计数器。
标签: java arrays nullpointerexception