企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 如何在 Java 中遍历`ArrayList` > 原文: [https://beginnersbook.com/2013/12/how-to-loop-arraylist-in-java/](https://beginnersbook.com/2013/12/how-to-loop-arraylist-in-java/) 之前我们分享了[`ArrayList`示例](https://beginnersbook.com/2013/12/java-arraylist/)和[如何在 Java ](https://beginnersbook.com/2013/12/how-to-initialize-an-arraylist/)中初始化`ArrayList`。在这篇文章中,我们将分享如何在 Java 中迭代(循环)`ArrayList`。 循环`ArrayList`有四种方法: 1. `for`循环 2. 高级循环 3. `while`循环 4. 迭代器 让我们看看下面的例子 - 我已经使用了所有提到的方法来迭代列表。 ```java import java.util.*; public class LoopExample { public static void main(String[] args) { ArrayList<Integer> arrlist = new ArrayList<Integer>(); arrlist.add(14); arrlist.add(7); arrlist.add(39); arrlist.add(40); /* For Loop for iterating ArrayList */ System.out.println("For Loop"); for (int counter = 0; counter < arrlist.size(); counter++) { System.out.println(arrlist.get(counter)); } /* Advanced For Loop*/ System.out.println("Advanced For Loop"); for (Integer num : arrlist) { System.out.println(num); } /* While Loop for iterating ArrayList*/ System.out.println("While Loop"); int count = 0; while (arrlist.size() > count) { System.out.println(arrlist.get(count)); count++; } /*Looping Array List using Iterator*/ System.out.println("Iterator"); Iterator iter = arrlist.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } } } ``` 输出: ```java For Loop 14 7 39 40 Advanced For Loop 14 7 39 40 While Loop 14 7 39 40 Iterator 14 7 39 40 ``` 在下面的评论部分,Govardhan 问了一个问题:他问,如何使用[`Enumeration`](https://docs.oracle.com/javase/7/docs/api/java/util/Enumeration.html)迭代`ArrayList`。 Govardhan 这里是代码: ### 如何使用`Enumeration`接口迭代`arraylist`元素 ```java import java.util.Enumeration; import java.util.ArrayList; import java.util.Collections; public class EnumExample { public static void main(String[] args) { //create an ArrayList object ArrayList<String> arrayList = new ArrayList<String>(); //Add elements to ArrayList arrayList.add("C"); arrayList.add("C++"); arrayList.add("Java"); arrayList.add("DotNet"); arrayList.add("Perl"); // Get the Enumeration object Enumeration<String> e = Collections.enumeration(arrayList); // Enumerate through the ArrayList elements System.out.println("ArrayList elements: "); while(e.hasMoreElements()) System.out.println(e.nextElement()); } } ``` 输出: ```java ArrayList elements: C C++ Java DotNet Perl ```