【问题标题】:Does not iterate through the class that implement Iterable不遍历实现 Iterable 的类
【发布时间】:2019-10-27 22:53:43
【问题描述】:

下面的代码给了我不编译给我以下错误:“foreach 不适用于类型 'Bag'”。

我不明白问题出在哪里,因为“Bag”类正在实现“Iterable”,所以我猜,循环应该将“Bag”视为“Iterable”。请问,你能帮我澄清一下情况吗?

class Bag<Item> implements Iterable<Item> {
private Node first;

private class Node {
    Item item;
    Node next;
}

public void add(Item item) {
    Node oldfirst = first;
    first = new Node();
    first.item = item;
    first.next = oldfirst;
}

public Iterator<Item> iterator() {
    return new ListIterator();
}

private class ListIterator implements Iterator<Item> {
    private Node current = first;

    public boolean hasNext() {
        return current != null;
    }

    public void remove() {}

    public Item next() {
        Item item = current.item;
        current = current.next;
        return item;
    }

}

public static void main(String[] args) {
    Bag<Integer> a = new Bag();
    a.add(5);
    a.add(10);
    for (int w : a) {
        System.out.println(w.iterator());
    }
 }
}

【问题讨论】:

  • 包从何而来?如果不编译就不能实现Iterable。
  • 其实it works对我来说

标签: java loops iterator iteration iterable


【解决方案1】:

问题出在您的main 方法中。经过几个简单的修复后,这个工作:

public static void main(String[] args) {
    Bag<Integer> a = new Bag<>();
    a.add(5);
    a.add(10);
    for (int w : a) {
        System.out.println(w);
    }
}

首先,Bag 初始化 - &lt;&gt; 丢失,没有它就无法为我编译。

然后在println中,你不能调用w.iterator(),因为w是一个int,它没有这样的方法。不知道你想在那里实现什么。

【讨论】:

  • 是的,我知道我不能遍历整数。我只是在搞砸事情以了解为什么这不起作用,并且在发布问题时忘记将 w.iterator() 重新更改为 w。但是,我的问题在于循环本身。在为 (int w : a) 编写时,它给出了上面提到的错误。
【解决方案2】:
public static void main(String[] args) {
    Bag<Integer> a = new Bag();
    a.add(5);
    a.add(10);
    for (int w : a) {
        System.out.println(w);
    }
}

你不能迭代整数。它用于迭代集合。你只需要改变 System.out.println(w);

如果你使用的是 java 8 然后就可以直接使用迭代了

a.iterator().forEachRemaining(n -> System.out.println(n));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 2021-01-11
    相关资源
    最近更新 更多