How to remove elements using Java iterators?
To remove elements using a Java iterator, you can follow these steps:
- First, create an iterator object and associate it with the collection to be operated on. For example, if you want to operate on an ArrayList collection, you can use the following code to create an iterator:
- Create an iterator for the ArrayList that holds String elements.
- Traverse the elements in a collection using a while loop. Within the loop, you can use the hasNext() method of the iterator to check if there is another element, and use the next() method to get the current element. For example:
- while there are still elements in the iterator, remove the element at this point.
- Perform deletion operations within the loop. You can use the remove() method of an iterator to delete the current element. For example:
- remove the current element from the iterator.
The complete sample code is shown below:
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorExample {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("元素1");
arrayList.add("元素2");
arrayList.add("元素3");
Iterator<String> iterator = arrayList.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("元素2")) {
iterator.remove();
}
}
System.out.println(arrayList); // 输出:[元素1, 元素3]
}
}
Warning: When deleting elements using an iterator, you must use the iterator’s remove() method for deletion, instead of directly using the collection’s remove() method, as using the remove() method directly can result in a ConcurrentModificationException.