简体   繁体   中英

Why can't I use foreach on my Class?

I'm trying to use my custom class with an iterator, but it can't iterate on the elements using foreach . How can I deal with it?

public class FCSOfOtherClass<Double> {
private int n;
private Double[] a;

public FCSOfOtherClass(int cap) {
    a = (Double[]) new Object[cap];
}

public void push(Double dou) {
    if (a.length == n) {
        this.resize(2 * a.length);
        a[n++] = dou;
    } else {
        a[n++] = dou;
    }
}

private void resize(int max) {
    Double[] newa = (Double[]) new Object[max];
    for (int i = 0; i < n; i++) {
        newa[i] = a[i];
        a = newa;
    }
}

public Boolean isEmpty() {
    return n == 0;
}

public Double pop() {
    Double dou = a[--n];
    a[n] = null;
    if (n > 0 && n == a.length / 2) {
        resize(a.length / 2);
    }
    return dou;
}

public int size() {
    return n;
}

public Iterator<Double> iterator() {
    return new RAIterator();
}

private class RAIterator implements Iterator<Double> {
    private int i = n;

    @Override
    public boolean hasNext() {
        return i > 0;
    }

    @Override
    public Double next() {
        return a[--i];
    }

    @Override
    public void remove() {

    }

    @Override
    public void forEachRemaining(Consumer<? super Double> action) {

    }

This is my main method:

public static void main(String[] args) {
    FCSOfOtherClass<Integer> fcs = new FCSOfOtherClass<>(100);
    int i = 0;
    while (!StdIn.isEmpty()) {
        fcs.push(++i);
    }
    for (int j:fcs) {
        StdOut.print(j);
    }
}

When I run this, I get an error telling me that foreach is not applicable to my type.

Your class FCSOfOtherClass does not implement java.lang.Iterable . The "foreach" loop only works on arrays and instances of Iterable .

You can address this by making your class implement Iterable :

public class FCSOfOtherClass implements java.lang.Iterable<Double> {
    ...
}

This requires that you provide an implementation for the interface method iterator() . Your sample code shows that you already do:

public Iterator<Double> iterator() {
    return new RAIterator();
}

This is covered in the Java Language Specification, section 14.14.2: The enhanced for statement :

The type of the Expression must be Iterable or an array type (§10.1), or a compile-time error occurs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM