温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java While循环如何遍历

发布时间:2026-08-30 03:16:35 来源:亿速云 阅读:86 作者:小樊 栏目:编程语言

在 Java 中,while 循环可以用来遍历数组、集合、字符串等。下面按常见场景给你示例说明。


一、while 循环遍历数组

示例:遍历 int 数组

int[] arr = {1, 2, 3, 4, 5};

int i = 0;
while (i < arr.length) {
    System.out.println(arr[i]);
    i++;
}

✅ 执行流程:

  1. 定义索引 i = 0
  2. 判断 i < arr.length
  3. 执行循环体
  4. i++ 后回到条件判断

二、while 循环遍历字符串

示例:遍历字符串中的每个字符

String str = "hello";

int i = 0;
while (i < str.length()) {
    System.out.println(str.charAt(i));
    i++;
}

三、while 循环遍历集合(List)

示例:遍历 ArrayList

List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");

int i = 0;
while (i < list.size()) {
    System.out.println(list.get(i));
    i++;
}

四、while + Iterator 遍历集合(推荐安全方式)

List<String> list = new ArrayList<>();
list.add("A");
list.add("B");

Iterator<String> it = list.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}

✅ 优点:

  • 可以在遍历时安全删除元素
  • 避免 ConcurrentModificationException

五、while 循环遍历 Map

遍历 key

Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);

Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
    String key = it.next();
    System.out.println(key + " = " + map.get(key));
}

遍历 entrySet(推荐)

Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry<String, Integer> entry = it.next();
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

六、while 和 for 的简单对比

循环类型 适合场景
while 循环次数不确定
for 遍历固定长度结构
// for 更简洁
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

七、常见错误示例 ❌

while (i < arr.length) {
    System.out.println(arr[i]);
    // 忘记 i++,导致死循环
}

如果你有具体场景(比如遍历树、链表、用户输入),可以告诉我,我可以给你更贴切的示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI