Java 'for each' 循环是如何工作的? [英] How does the Java 'for each' loop work?

查看:38
本文介绍了Java 'for each' 循环是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Consider:

List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList

for (String item : someList) {
    System.out.println(item);
}

What would the equivalent for loop look like without using the for each syntax?

解决方案

for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
    String item = i.next();
    System.out.println(item);
}

Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for ( : ) idiom, since the actual iterator is merely inferred.

As was noted by Denis Bueno, this code works for any object that implements the Iterable interface.

Also, if the right-hand side of the for (:) idiom is an array rather than an Iterable object, the internal code uses an int index counter and checks against array.length instead. See the Java Language Specification.

这篇关于Java 'for each' 循环是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆