An error is reported when traversing the list collection to delete elements
When traversing the list collection to delete elements, problems such as index out of bounds exception or incomplete content traversal will occur
Example:
List< String> al = new ArrayList< String>();
al.add(“12”);
al.add(“1”);
al.add(“13”);
int size = al.size();
Problem 1: index out of bounds exception in thread “main” java.lang.indexoutofboundsexception: index: 2, size: 2
for(int i=0; i< size; i++){
if(“1”.equals(al.get(i)))
al.remove(i);
}
Problem analysis: delete an element after meeting the conditions. There are only two elements in the collection. Only al. Get (0) and al. Get (1) can be used. When al. Get (2) obtains elements, the index exceeds the limit. Some students may want to change the number of sizes above to al. Size (). Although the index crossing problem is solved, there is a problem of incomplete traversal
Problem 2: incomplete content traversal
for(int i=0; i< al.size(); i++){
if(“1”.equals(al.get(i)))
al.remove(i);
}
Problem analysis: delete an element after meeting the conditions, and no longer cycle the third element
Correct code:
Iterator< String> it = al.iterator();
while(it.hasNext()){
if(“1”.equals(it.next()))
it.remove();
}
Similar Posts:
- [Solved] Exception in thread “main” java.util.ConcurrentModificationException
- Mybatis where 1 = 1 and Tags
- Occlusion problem of SVG Z-index layer
- Java container — unsupported operation exception
- [Solved] Arrays.asList() Error: java.lang.UnsupportedOperationException
- cannot simultaneously fetch multiple bags
- JAVA set to determine the null: List.isEmpty() & null == List && List.size()==0
- [Solved] Sping controller Receives list entity parameter Error: nested exception is java.lang.IndexOutOfBoundsException: Index: 256, Size: 256
- Pytest @pytest.mark.parametrize Example
- When using angularjs procedure, track by $index of NG repeat