Java face question

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.