我们可以使用for-each循环来迭代Iterator类型的对象吗? [英] Can we use for-each loop for iterating the objects of Iterator type?

查看:101
本文介绍了我们可以使用for-each循环来迭代Iterator类型的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们执行以下操作,则会收到错误:

If we do the following we get error:

class FGH{
public static Iterator reverse(List list) {
     Collections.reverse(list);
     return  list.iterator();
     }
     public static void main(String[] args) {
     List list = new ArrayList();
     list.add("1"); list.add("2"); list.add("3");
     /*for(Iterator it:reverse(list))
     Iterator it=reverse(list);*/
     for (Object obj: reverse(list))
     System.out.print(obj + ", ");}}

但如果我们修改这样的代码我们没有得到错误,所以它是否意味着我们不能迭代Iterator类型的对象? :

but if we modify the code like this we don't get error,so is it mean that we can't iterate the objects of Iterator type? :

class FGH{
public static Iterator reverse(List list) {
     Collections.reverse(list);
     return  list.iterator();
     }
     public static void main(String[] args) {
     List list = new ArrayList();
     list.add("1"); list.add("2"); list.add("3");
     Iterator it=reverse(list);
     while(it.hasNext()){
    Object obj=it.next();
    System.out.println(obj);
     }
     }}


推荐答案

第一个示例中的 for 循环期望 reverse(list) Iterator的集合,当然不是。这就是为什么这个例子不起作用的原因。

The for loop in your first example expects that reverse(list) is a collection of Iterator, which of course it isn't. That's why that example won't work.

一般来说,你只能在实现<的类上使用 foreach code>可迭代。 Iterator 不是这些类别中的一个。

In general, you can only use foreach on classes that implement Iterable. Iterator is not one of these classes.

参见 http://java.sun.com/j2se/1.5.0/docs/api/java/lang /Iterable.html

这篇关于我们可以使用for-each循环来迭代Iterator类型的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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