Note that there are some explanatory texts on larger screens.

plurals
  1. PORearranging array when it has a null position
    text
    copied!<p>I have this code that searches one object in an array and removes it. I'm having a problem with its position, since some other methods work with this array (and it gives me a NullPointerException every time). My method looks like this:</p> <pre><code>public void deleteHotel(String hotelName) { for (int i = 0; i &lt; 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 &gt; 1 &amp;&amp; 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 &lt; 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 &lt; 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; } } } </code></pre> <p>When I use other methods (for example, one that returns the implemented toString()s of each object) it gives me a NullPointerException. Can you guys identify the error in the code? Much appreciated...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload