迭代器的remove()方法
时间: 2023-05-31 17:06:17 浏览: 96
迭代器的remove()方法用于从集合中删除迭代器最后一次返回的元素。具体来说,它会删除集合中迭代器最后一次返回的元素,并且如果在调用remove()方法之前调用next()方法,则next()方法返回的元素将是迭代器的下一个元素。
注意:调用remove()方法之前必须先调用next()方法,否则会抛出IllegalStateException异常。
示例代码:
```java
List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.equals("banana")) {
iterator.remove();
}
}
System.out.println(list); // [apple, cherry]
```
相关问题
迭代器remove数组表
可以使用迭代器的remove方法来删除数组中的元素。具体步骤如下:
1. 定义一个数组,并使用Arrays.asList()方法将其转换为List类型。
```
Integer[] arr = {1, 2, 3, 4, 5};
List<Integer> list = new ArrayList<>(Arrays.asList(arr));
```
2. 获取List的迭代器。
```
Iterator<Integer> iterator = list.iterator();
```
3. 使用while循环遍历List中的元素,并使用迭代器的remove()方法删除满足条件的元素。
```
while (iterator.hasNext()) {
Integer num = iterator.next();
if (num % 2 == 0) {
iterator.remove();
}
}
```
4. 最后,将List转换回数组类型,即可得到删除后的数组。
```
Integer[] result = list.toArray(new Integer[0]);
```
迭代器的remove
迭代器的remove()方法是用来删除集合中当前迭代器指向的元素的。它可以在遍历集合时删除元素,而不会抛出ConcurrentModificationException异常。但是需要注意的是,如果在调用remove()方法之前没有调用next()方法,则会抛出IllegalStateException异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![avi](https://img-home.csdnimg.cn/images/20210720083319.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)