1.Java ArrayList time Elapsed Delete element
The key to the problem is whether the interviewer is using the ArrayList remove () or the Iterator remove () method. is to use the correct way to implement the sample code that removes the element during traversal without the concurrentmodificationexception exception.
When we traverse the ArrayList, we need to delete the element that satisfies the condition, and the general practice is as follows:
ArrayList<String> coorList = new ArrayList<String>();... ...for (int i = 0; i < coorList.size(); i++){ if (coorList.get(i).equals("hello")) { coorList.remove(i); }}
However, there may be problems with these practices, such as the inability to delete all the elements that satisfy the criteria, and the correct approach is to use an iterator, as follows
Iterator<String> iter = coorList.iterator(); while(iter.hasNext()){ if(iter.next().equals("hello")){ iter.remove(); } }
But this approach can also produce another exception: Java.util.NoSuchElementException, Iter.next always points to the next element, that is, ITER crosses the border. Therefore, we only need to do the following:
Iterator<String> iter = coorList.iterator(); while(iter.hasNext()){ **String s = iter.next();//新建一个对象** if(s.equals("hello")){ iter.remove(); } }
This is done to safely traverse the elements in the delete ArrayList.
Java face question