Four ways to traverse the Java list

Source: Internet
Author: User

There are four main ways to traverse a list object in Java:

1. For loop--normal for loop

2. Advanced for loop--premium for loop

3. Iterator loop--iterator traversal

4. While Loop--while loop

Refer to the following code for details:

Import Java.util.arraylist;import Java.util.iterator;import java.util.List;
public class Main {public static void main (String []args) {//create list list<integer> LST = new Arraylist<> (); Add some elements lst.add (1); Lst.add (2); Lst.add (3); Lst.add (4); 1. For Loop System.out.println ("1. For Loop "); for (int i = 0; i < lst.size (); + + i) {System.out.println (Lst.get (i)); }//2. Advanced for Loop System.out.println ("2. Advanced for Loop "); for (int val:lst) {System.out.println (val); }//3. Iterator Loop System.out.println ("3. Iterator Loop "); Iterator<integer> it = Lst.iterator (); while (It.hasnext ()) {System.out.println (It.next ()); }//4. While Loop System.out.println ("4. While loop "); int i = 0; while (I < lst.size ()) {System.out.println (Lst.get (i)); + + i; } }}

Reference: http://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/

Four ways to traverse the Java list

Related Article

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.