java list.remove pit

Used in the process of doing the project, list.remove, stepped on a few pit, look at this record

1.

List<Integer> list

list.remove(i);

When the element within the list is Integer type, pay attention to remove the parameter is an element, or the number of elements.

2.

In the remove list is an exception occurs java.util.ConcurrentModificationException

Need to use iterators remove, you can not directly use the remove list

public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
list.add("333");
list.add("444");
list.add("555");
list.add("666");
list.add("777");
list.add("888");

Iterator<String> it=list.iterator();
int i=0;
while (it.hasNext()){
String s=it.next();
i++;
if(i==2){
it.remove();
System.out.println("remove:"+s);
System.out.println();
}
}
}

3.
for(int i=0;i<list.size();i++){
  list.remove (I);
}
traversal list when executed remove, size becomes smaller in the list may be generated out of range, it is recommended to remove a traverse iterator

Guess you like

Origin www.cnblogs.com/jakin3130/p/10948679.html