0

The code looks like this:

for (int i = 0; i < fileList.size(); i++) {
        System.out.println("File List size is " + fileList.size());

        String fileName = (fileList.get(i).fileName);


            String accountNumber =  accountNumber(fileName);
            System.out.println(accountNumber);
            if(accountNumber.equals("fail")) {

                decode(dirLocation+fileName,"C:/.../.../.../ChunkTestInvalid/"+fileName);
                fileList.remove(i);
                System.out.println("File removed at first stage: "+fileName);
            }
            else {..........

I'm trying to setup a situation where files that don't match criteria in the accountNumber method get decoded to a particular folder on my machine and removed from fileList, which is an ArrayList for a custom Object. The fileList.remove(i) call is removing SOMETHING from the ArrayList (as the fileList.size() value is decreasing) but it's removing something other the object located at fileList.get(i) at the start of the for loop, because it keeps returning the same object.

What is the correct way to identify that the object I want to remove from the ArrayList is the one that exists at fileList.get(i) at that time?

David Martin
  • 95
  • 1
  • 2
  • 9
  • 2
    Loop from the end to the start of the list. Otherwise, every time you remove an element, the indices of the remaining elements change, and you skip elements. – JB Nizet Jul 31 '19 at 16:58
  • Or just use `Iterator`s. – M. Prokhorov Jul 31 '19 at 16:59
  • 3
    Possible duplicate of [Remove elements from collection while iterating](https://stackoverflow.com/questions/10431981/remove-elements-from-collection-while-iterating) – Scott Hunter Jul 31 '19 at 17:00

1 Answers1

0

You can try using iterator like this -

List<String> fileList;
Iterator<String> iter = fileList.iterator();
while (iter.hasNext()) {
  System.out.println("File List size is " + fileList.size());

  String fileName = (iter.next().fileName);


  String accountNumber =  accountNumber(fileName);
  System.out.println(accountNumber);
  if(accountNumber.equals("fail")) {

    decode(dirLocation+fileName,"C:/.../.../.../ChunkTestInvalid/"+fileName);
    iter.remove();
    System.out.println("File removed at first stage: "+fileName);
  }
  else {..........
}
Anand Vaidya
  • 1,374
  • 11
  • 26