用java修改上面的代码
时间: 2024-02-28 12:57:45 浏览: 25
好的,下面是使用Java修改后的代码:
```java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Example04 {
public static void main(String[] args) {
List<String> list = new ArrayList<>(); // 创建集合
list.add("张三");
list.add("李四");
list.add("王五");
Iterator<String> it = list.iterator(); // 获取Iterator对象
while (it.hasNext()) { // 判断集合中是否有下一个元素
String str = it.next(); // 取出集合中的元素
if ("张三".equals(str)) { // 判断集合中的元素是否为“张三”
it.remove(); // 删除集合中找到的元素
}
}
System.out.println(list);
}
}
```
这段代码中,我们将集合的类型声明为 `List<String>`,使用泛型来指定集合的元素类型,增加了代码的可读性。
另外,我们使用了 `Iterator` 的 `remove()` 方法来删除集合中的元素,避免了 `ConcurrentModificationException` 异常的出现。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)