list is an ArrayList of objects

list is an ArrayList object, which option code is filled in //todo delete, can the object saved in a list be deleted correctly and safely during the Iterator traversal process? ( )

A) it.remove();

B) list.remove(obj);

C) list.remove(index);

D) list.remove(obj,index);

Iterators support safe removal of objects from the source collection by simply calling remove() on the Iterator. The advantage of this is to avoid ConcurrentModifiedException, when the Iterator is opened to iterate the collection, and the collection is being modified at the same time. Some collections do not allow removing or adding elements while iterating, but it is safe to call the Iterator's remove() method.

 

If the remove() method of the collection is called during the loop, although the loop will not cause an error, it will cause the element to be deleted incompletely, for example:
for(int i=0;i<list.size();i++){
     list .remove(i);
 }
The size of list.size() changes during the loop, which leads to a logic error, which eventually leads to incomplete deletion of elements in the list.
 So, if you want to remove an element in the collection in the loop statement, you need to use the iterator's remove() method, because its remove() method not only removes the element, but also maintains a flag to record Is it currently in a deleteable state, for example, you cannot call its remove() method twice in a row, with at least one next() method call before the call.

 

The source code is described as follows: ArrayList inherits AbstractList, and a modCount in AbstractList represents the number of times the collection is modified. In the iterator method of ArrayList, it will judge whether expectedModCount and modCount are equal. If they are equal, continue to execute, and an error will be reported if they are not equal. Only the remove method of the iterator will make expectedModCount and modCount equal after calling its own remove method, so it is safe.

 

Source:

https://www.nowcoder.com/test/question/done?tid=14076599&qid=15549#summary

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325453012&siteId=291194637