0

I have removed elements from Arraylist using iterator. But after removing size is not reduced and values remains same in Arraylist. I have used ArrayList as a class level variable. Doesn't know why it is not working. Below is my code,

public class MyClass{
private ArrayList<String> valueArrayList;
Iterator itr = valueArrayList.iterator();
                while (itr.hasNext())
                    if (validateFile((String) itr.next())) {

                        Log.d(LOG_TAG, "values removed");

                    } else
                        itr.remove();
}
5
  • Why do you have itr.remove() in else case when validation log displayed in if condition (I.e. "values removed"). Commented Nov 22, 2019 at 6:43
  • @Jeel Vankhede I have method for checking whether a file exist or not. So I am passing a string to it. If file path exist,then it will return true else false. If file doesn't exist, then I want to remove it from the list Commented Nov 22, 2019 at 6:46
  • @Jeel Vankhede I am using the ArrayList in some other place in the class. But after removing it is not updating my Arraylist. Commented Nov 22, 2019 at 6:49
  • try to put the log and check that else block getting reached? Commented Nov 22, 2019 at 6:50
  • 1
    Point is.. you're getting log ''values removed" when you're having true flag indicating file exists. So that log is generating ambiguity. Commented Nov 22, 2019 at 6:52

1 Answer 1

3

It's should be

Iterator<String> itr = valueArrayList.iterator();
while (itr.hasNext()) {
    // If file doesn't exist
    if (!validateFile(itr.next())) {
        itr.remove(); // delete from list
        Log.d(LOG_TAG, "values removed");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.