Java error-prone knowledge points (1)-about ArrayList the remaining elements are immediately queued after the element is removedOriginal October 20, 2014 15:14:35 Tags: Java error knowledge Point/ArrayList remove elements, and then rearrange 1303
Help a netizen to answer a question, found such a mistake knowledge point, now summarized as follows:
1, Easy wrong point:
Once the element is removed, the remaining elements are immediately ArrayList, and his size () is immediately reduced and error prone during the loop. (Expansion: Whether it is feasible to extend to all collections)
2, easy to Error point analysis:
When the For loop traverses ArrayList, the size () of the collection is immediately reduced by 1 when the element is removed from the loop
The remaining elements are rearranged, removed from the lower rcas of the element behind the element, that is, the following element small RCAs minus 1
The second parameter I < List.size () in the For loop at this point is not the size of the original collection, but is 1 smaller than the previous one
And the value of the loop variable i is still increasing normally.
If you continue to traverse the collection, you can easily omit an element
3. Example Analysis:
The purpose of this instance is to remove the wrong version of the URL (1) with the # character in the collection:
[java] View plain copy <span style= "font-family:kaiti_gb2312;font-size:18px;" >import java.util.ArrayList; public class goulv { public static void main (String[] args) throws Exception { arraylist<string> urls = new ArrayList<String> (); urls.add ( "Http://www.baidu.com"); urls.add ("http:/#/ Www.baidu.com "); urls.add (" http://www#.zxitb.com "); urls.add ("http://www.zxitb.com"); int index; for (int i = 0; i < urls.size () i++) { index = -1; string url = urls.get (i); index = url.indexof (' # '); if (index != -1) { urls.remove (URL); }else { system.out.println (URL); } } for (Int i = 0; i < urls.size (); i++) { system.out.println ("Remove # After the url : " + urls.get (i)); } } } ----------------------------------------------- output is: http:// www.baidu.com http://www.zxitb.com Remove the url : http://www.baidu.com after the # Remove the url : http after the #: