Two ways of traversing List in Java

You can refer to the second method in the article Notepad++ to compile and run java code_notepad++ how to run java code_No1's Blog of Xijin-CSDN Blog to test the following code.

In java, there are two ways to traverse List using for loop and for-each loop.

1. Use for loop to traverse List

2. Use for-each to traverse the List

Note: When using the for-each loop, you cannot modify the elements in the List. If you need to modify the elements, you should use the for loop to traverse.

The example code is as follows:

import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        // 添加元素
        list.add("a");
        list.add("b");
        list.add("c");

        // 1.使用for循环遍历List
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

        // 2.使用for-each循环遍历
        for (String element : list) {
            System.out.println(element);
        }
    }
}

operation result:

 

Guess you like

Origin blog.csdn.net/xijinno1/article/details/131407574