java list删除元素
时间: 2024-01-15 19:18:55 浏览: 93
以下是两种Java中List删除元素的例子:
1. 使用普通for循环遍历删除元素:
```java
List<String> nameList = new ArrayList<>(list);
for (int i = nameList.size() - 1; i >= 0; i--) {
String str = nameList.get(i);
if (str.startsWith("test")) {
nameList.remove(i);
}
}
System.out.println(nameList);
```
2. 使用迭代器遍历删除元素:
```java
List<String> nameList = new ArrayList<>(list);
Iterator<String> iterator = nameList.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
if (str.startsWith("test")) {
iterator.remove();
}
}
System.out.println(nameList);
```
阅读全文