Enhanced for loop usage ___arraylist array implementation use subscript best, LinkedList use Enhanced (reprint)

Source: Internet
Author: User
Summarize:

1, the disadvantage of For-each cycle: lost the index information.

When traversing a collection or array, if you need to access the index of a collection or array, it is best to use the old-fashioned way to loop or traverse, rather than using an enhanced for loop, because it loses subscript information.

Enhanced for loop usage

1. The effect of first enhancing for loop and iterator traversal is the same, it is said that the internal of the enhanced for loop is called Iteratoer implementation,

However, there are some drawbacks to enhancing the For loop, such as not being able to dynamically delete collection contents in an enhanced loop. Cannot get subscript and so on.
2.ArrayList because of the use of arrays implementation, so the subscript is clear, it is best to use the normal loop.
3. For LinkedList because it takes an element to get back from the beginning, it is recommended to use an enhanced for loop, which is iterator.
The following example can prove

Press CTRL + C to copy code press CTRL + C to copy code

Use ArrayList to run the results as follows

Change the ArrayList to LinkedList, I have a memory overflow here, the result is as follows

So the list is changed to 50000 and the results are as follows


So when you use it, it's good to choose.

Enhanced for loop usage ___arraylist array implementation use subscript best, LinkedList use Enhanced (reprint)

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.