Java in the operation of the list is very frequent, especially for the list start traversal, these operations we will, but also very familiar with, but the Java list to delete elements, remove list elements are not familiar with it, can be said to be unfamiliar, is the actual operation is also prone to error, Let's take a look at how to remove elements from the list in Java below.
- public class Test {
- public static void Main (string[] args) {
- String str1 = new String ("ABCDE");
- String str2 = new String ("ABCDE");
- String str3 = new String ("ABCDE");
- String STR4 = new String ("ABCDE");
- String STR5 = new String ("ABCDE");
- List List = new ArrayList ();
- List.add (STR1);
- List.add (STR2);
- List.add (STR3);
- List.add (STR4);
- List.add (STR5);
- System.out.println ("list.size () =" + list.size ());
- for (int i = 0; i < list.size (); i++) {
- if ((String) list.get (i)). StartsWith ("ABCDE")) {
- List.remove (i);
- }
- }
- System.out.println ("after remove:list.size () =" + list.size ());
- }
- }
What do you think the result of this program is printed out?
Java code
- The result of the operation is not:
- List.size () =5
- After Remove:list.size () =0
But:
Java code
- List.size () =5
- After Remove:list.size () =2
What's going on here? How do you want to remove the elements from the list?
Cause: After the list removes an element each time, the subsequent elements move forward, and if I=i+1 is executed, the element that has just been moved is not read.
How to solve? There are three ways to solve this problem:
1. Traverse the list backwards
Java code
- for (int i = List.size ()-1; i > =0; i--) {
- if ((String) list.get (i)). StartsWith ("ABCDE")) {
- List.remove (i);
- }
- }
2. Move the I back after each element is removed
Java Code
- for (int i = 0; i < list.size (); i++) {
- if ((String) list.get (i)). StartsWith ("ABCDE")) {
- List.remove (i);
- I=i-1;
- }
- }
3. Use the Iterator.remove () method to remove
Java Code
- for (Iterator it = List.iterator (); It.hasnext ();) {
- String str = (string) it.next ();
- if (Str.equals ("Chengang")) {
- It.remove ();
- }
- }
- Http://blog.sina.com.cn/s/blog_621b6f0e0100s5n5.html
List how remove is particularly error prone