3 Ways to traverse the list collection

Source: Internet
Author: User

  1. Package com.sort;
  2. Import java.util.ArrayList;
  3. Import Java.util.Iterator;
  4. Import java.util.List;
  5. /**
  6. * List of three kinds of traversal
  7. *
  8. */
  9. Public class Listtest {
  10. public static void Main (string[] args) {
  11. list<string> list = new arraylist<string> ();
  12. List.add ("a");
  13. List.add ("B");
  14. List.add ("C");
  15. List.add ("C"); Can add duplicate data
  16. //Traversal method one
  17. For (iterator<string> Iterator = List.iterator (); Iterator.hasnext ();) {
  18. String value = Iterator.next ();
  19. System.out.println (value);
  20. }
  21. //Traversal method two
  22. For (String value:list) {
  23. System.out.println (value);
  24. }
  25. //Traverse method three
  26. For (int i=0;i<list.size (); i++) {
  27. System.out.println (List.get (i));
  28. }
  29. }
  30. }


Comparative analysis of three types of traversal:

Method One traversal:

Data locks are performed during execution, and performance is slightly worse, and you can only invoke the It.remove method if you want to remove an element from the loop.

Method two times:

Internal invocation of the first

Method Three traversal:

Internal not locked, the most efficient, but when writing multi-threading to consider the problem of concurrent operation

The two main implementations of the list interface, ArrayList, and LinkedList, can be used in such a way to traverse

A comparative analysis of ArrayList and LinkedList
A) ArrayList the bottom of the array implementation, linkedlist the bottom of the two-way linked list implementation.
b) When performing an insert or delete operation, it is better to use LinkedList.
c) When performing a search operation, it is better to use ArrayList.

To be blunt, sequential storage and chained storage in data structures

3 Ways to traverse the list collection

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.