gpt4 book ai didi

java - 为什么我不能在我的类(class)上使用 foreach?

转载 作者:行者123 更新时间:2023-11-29 06:52:00 25 4
gpt4 key购买 nike

我正在尝试将我的自定义类与迭代器一起使用,但它无法使用 foreach 对元素进行迭代。我该如何处理?

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) {

}

这是我的主要方法:

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);
}
}

当我运行它时,我收到一条错误消息,告诉我 foreach 不适用于我的类型。

最佳答案

您的类 FCSOfOtherClass 没有实现 java.lang.Iterable。 “foreach”循环仅适用于 Iterable 的数组和实例。

您可以通过让您的类实现Iterable 来解决这个问题:

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

这需要您提供接口(interface)方法 iterator() 的实现。您的示例代码表明您已经这样做了:

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

这包含在 Java 语言规范中,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.

关于java - 为什么我不能在我的类(class)上使用 foreach?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44954585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com