iterator.remove();
时间: 2024-05-10 07:20:03 浏览: 63
浅谈java Iterator.remove()方法的用法(详解)
This code removes the current element from the collection being iterated over by the iterator. It is a method provided by the Iterator interface in Java.
Here's an example of how it can be used:
```
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
int number = iterator.next();
if (number % 2 == 0) {
iterator.remove(); // removes even numbers from the list
}
}
System.out.println(numbers); // [1, 3]
```
In this example, we create a list of numbers and then create an iterator to iterate over its elements. We use the `remove()` method to remove even numbers from the list while iterating over it. Finally, we print the list to confirm that even numbers have been removed.
阅读全文