java - Removing from array and manage spaces after removing a worker -


i have method removes worker if name starts assigned letter accepted removeworker() method. can explain how second for loop working?

public void removeworker(string s) {     if (index == 0) {         system.out.println("there worker in array!");         return;     }     (int = 0; < index; i++) {         if (worker[i].getname().startswith(s)) {             (int j = i; j < index - 1; j++) {                 worker[j] = worker[j + 1];             }             worker[--index] = null;             i--;         }     } } 

the second loop moves workers 1 place closer start of array. done avoid "holes" in array (which occur if set element null). happens:

if(worker[i].getname().startswith(s))   

this checks if worker index should removed.

    for(int j = i; j < index - 1; j++)      { 

this for-loop iterates on workers index greater or equal i, hence starting worker removed. stops second last index, accesses worker index j + 1.

        worker[j] = worker[j + 1]; 

this here moves worker index j + 1 position j. overwrites worker removed worker next higher index. other workers shifted.

    }     worker[--index] = null; 

here last worker set null, saved in second last position during loop. ensures last worker not in array twice. index (the number of workers) decremented --index there 1 worker less in list.

    i--; } 

now decremented index of next worker check , loop increment again. without worker after worker removed not checked.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -