java - Rearranging array when it has a null position -
i have code searches 1 object in array , removes it. i'm having problem position, since other methods work array (and gives me nullpointerexception every time). method looks this:
public void deletehotel(string hotelname) { (int = 0; < this.hoteis.length; i++) { if (this.hoteis[i].getname().equalsignorecase(nomehotel)) { //searches array, looking object has inputted name this.hoteis[i] = null; //makes object null if (this.hoteis.length > 1 && this.hoteis[this.hoteis.length - 1] != null) { //for arrays lenghts bigger 1 (since there's no problem array 1 position) (int x = i; x < this.hoteis.length; x++) { this.hoteis[x] = this.hoteis[x + 1]; //makes null position point next position has object, , position points object in next position , on } this.hoteis[this.hoteis.length - 1] = null; //since last positions same, make last 1 null hotel[] hoteistemp = new hotel[this.hoteis.length - 1]; for(int x = 0; x < this.hoteis.length - 1; x++){ //create new array 1 less position, , copy objects on old array new array, point old array new array hoteistemp[x] = this.hoteis[x]; } this.hoteis = hoteistemp; } = this.hoteis.length; } } }
when use other methods (for example, 1 returns implemented tostring()s of each object) gives me nullpointerexception. can guys identify error in code? appreciated...
i have tested function , see mean getting nullpointerexception, due array not resizing list - due conditional:
if (this.hoteis.length > 1 && this.hoteis[this.hoteis.length - 1] != null)
.
removing solved issue, here working function:
public static void deletehotel(string hotelname) { (int = 0; < hotels.length; i++) { if (hotels[i].getname().equalsignorecase(hotelname)) { //searches array, looking object has inputted name hotels[i] = null; //makes object null (int x = i; x < hotels.length -1; x++) hotels[x] = hotels[x + 1]; //makes null position point next position has object, , position points object in next position , on hotel[] hoteistemp = new hotel[hotels.length - 1]; for(int x = 0; x < hotels.length - 1; x++) //create new array 1 less position, , copy objects on old array new array, point old array new array hoteistemp[x] = hotels[x]; hotels = hoteistemp; break; } } }
though please consider using list of sort when needing use list changing size.
Comments
Post a Comment