list是一個ArrayList的對象,哪個選項的代碼填到//todo delete處。能夠在Iterator遍歷的過程中正確並安全的刪除一個list中保存的對象?()
Iterator it = list.iterator(); int index = 0; while (it.hasNext()) { Object obj = it.next(); if (needDelete(obj)) //needDelete返回boolean。決定是否要刪除 { //todo delete } index ++; }
A.it.remove(); B.list.remove(obj); C.list.remove(index); D.list.remove(index);
選擇 A
假設在循環的過程中調用集合的remove()方法,就會導致循環出錯。比如: for(int i=0;i<list.size();i++){ list.remove(...); } 循環過程中list.size()的大小變化了,就導致了錯誤。所以,假設你想在循環語句中刪除集合中的某個元素。就要用迭代器iterator的remove()方法。由於它的remove()方法不僅會刪除元素。還會維護一個標志,用來記錄眼下是不是可刪除狀態。比如,你不能連續兩次調用它的remove()方法,調用之前至少有一次next()方法的調用。