Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector.remove() for loop

I am programming a game and almost have the save-file system complete. I have two Vectors (one holds the name of the savegame, one holds the sessionID).

At launch, the program will read in data from a file and add that information to the Vectors. Then another method is called to check if the files shown in the Vector acctualy exist. If not, they will be removed from the Vectors. At the end, the Vectors are printed to and rewrite the file.

The problem I'm having is the for loop isn't checking every item in the Vector, because Vector.size() is decreasing when items are removed.Is there a better way to form the for loop, or is there a workaround I can use?

private static void slistCleanup() throws IOException {

          private static Vector<String> saveNames = new Vector<String>();
          private static Vector<Integer> sessionIDs = new Vector<Integer>();

    Scanner slistReader = new Scanner(new FileReader(sessionList));
    File tempSave;
    String path;
    int run = 1;
    String tempName = " ";
    int tempID = 0;

    for (int x = 0; x < saveNames.size(); x++) {

        path = currentDir + "\\saves\\" + sessionIDs.elementAt(x) + ".sav";
        tempSave = new File(path);

        System.out.println("-----------------------"); //debug
        System.out.println("current pass: " + run);
        System.out.println("tempSave Path: " + tempSave.getAbsolutePath()); //debug
        System.out.println("tempSave exists: " + tempSave.exists()); //debug
        System.out.println("-----------------------"); //debug
        run++; //debug

        if (!tempSave.exists()) {

            saveNames.remove(x);
            sessionIDs.remove(x);
        }
    }

    for (int x = 0; x < saveNames.size(); x++) {

        System.out.println(saveNames.elementAt(x));
        System.out.println(sessionIDs.elementAt(x));
    }

    slistReader.close();
}

If you need more code, let me know.

like image 924
Aaron Avatar asked Dec 01 '22 21:12

Aaron


2 Answers

Loop backwards:

for (int x = saveNames.size()-1; x >= 0; x--)
like image 166
Vincent van der Weele Avatar answered Dec 10 '22 11:12

Vincent van der Weele


One way that would require few changes to your existing code would be to traverse the vector in the reverse direction.

for (int x = saveNames.size() - 1; x >= 0; x--) {
   ...
}
like image 23
Andy Thomas Avatar answered Dec 10 '22 12:12

Andy Thomas