for-each循环只能在java.lang.Iterable的数组或实例上进行迭代 [英] for-each loop can only iterate over an array or an instance of java.lang.Iterable

查看:78
本文介绍了for-each循环只能在java.lang.Iterable的数组或实例上进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码不起作用.此代码有什么问题?编译器在for循环中抱怨 NumberList 不是 Iterable 类.

The following code doesn't work. What's wrong with this code? Compiler complains in the for loop that NumberList isn't a Iterable class.

在for-each循环中可以使用哪种类?如何使 NumberList 可迭代?我尝试使 NumberList实现Iterable ,但是它似乎不起作用,因为我不知道如何正确定义Iterator.

What kind of class can be used in for-each loop? How to make NumberList iterable? I tried making NumberList implement Iterable, but it doesn't seem to work because I don't know how to define the Iterator properly.

如果有人可以演示如何使此代码有效,或者将我链接到很棒的教程.

If someone could demonstrate how to make this code work, or link me to a tutorial that'd be great.

public class Test{
    public class NumberList{
        private int numItems;
        private Number[] numbers;

        public NumberList(int size){
            this.numbers = new Number[size];
            this.numItems=0;
        }

        public void add(Number n){
            this.numbers[this.numItems++]=n;
        }
    }

    public void printPairs() {
        ArrayList<Integer> num=new ArrayList<Integer>();

        NumberList numbers = new NumberList(50);
        numbers.add(4);
        numbers.add(5);
        numbers.add(6);

        for(Number n1: numbers){
            System.out.println(n1);
        }
    }
}

推荐答案

NumberList没有实现Iterable.就编译器而言,它只是任何其他类.

NumberList does not implement Iterable. As far as the compiler is concerned its just any other class.

您需要执行类似的操作

public class NumberList implements Iterable<Number> {

    private int numItems;
    private Number[] numbers;

    public NumberList(int size) {
        this.numbers = new Number[size];
        this.numItems = 0;
    }

    public void add(Number n) {
        this.numbers[this.numItems++] = n;
    }

    @Override
    public Iterator<Number> iterator() {
        return Arrays.asList(numbers).subList(0, numItems).iterator();
    }
}

这篇关于for-each循环只能在java.lang.Iterable的数组或实例上进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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