JAVA中LISt遍历时如何remove元素
- 1. import java.util.*;
- 2. public class object {
- 3. public static void main(String[] args) {
- 4. String str1 = new String("abcde");
- 5. String str2 = new String("abcde");
- 6. String str3 = new String("abcde");
- 7. String str4 = new String("abcde");
- 8. String str5 = new String("abcde");
- 9. List list = new ArrayList();
- 10. list.add(str1);
- 11. list.add(str2);
- 12. list.add(str3);
- 13. list.add(str4);
- 14. list.add(str5);
- 15. System.out.println("list.size()=" + list.size());
- 16. for (int i = 0; i < list.size(); i++) {
- 17. if (((String) list.get(i)).startsWith("abcde")) {
- 18. list.remove(i);
- 19. }
- 20. }
- 21. System.out.println("after remove:list.size()=" + list.size());
- 22. }
- 23. }
运行结果不是:
list.size()=5
after remove:list.size()=0
居然是:
list.size()=5
after remove:list.size()=2
原因:List每remove掉一个元素以后,后面的元素都会向前移动,此时如果执行i=i+1,则刚刚移过来的元素没有被读取。
解决方法:
1.倒过来遍历list
for (int i = list.size()-1; i > =0; i--) {
if (((String) list.get(i)).startsWith("abcde")) {
list.remove(i);
}
}
2.每移除一个元素以后再把i移回来
for (int i = 0; i < list.size(); i++) {
if (((String) list.get(i)).startsWith("abcde")) {
list.remove(i);
i=i-1;
}
}
3.使用iterator.remove()方法删除
for (Iterator it = list.iterator(); it.hasNext();) {
String str = (String)it.next();
if (str.equals("chengang")){
it.remove();
}
}