接口迭代器已经在Java中定义了什么?

Kra*_*ken 0 java iterator interface

接口是否Iterator已在java库中的某处定义(请注意术语).即

我要问的是,说我有一个arraylist,现在我写.

Iterator itr= new Iterator();
Run Code Online (Sandbox Code Playgroud)

但我从未定义过类似的东西

public interface Iterator{  // all the methods };
Run Code Online (Sandbox Code Playgroud)

我是否需要导入一些已定义此迭代器的包?

我来这里举个例子:

class BOX implements Comparable {

    private double length;
    private double width;
    private double height;

    BOX(double l, double b, double h) {
        length = l;
        width = b;
        height = h;
    }

    public double getLength() {
        return length;
    }

    public double getWidth() {
        return width;
    }

    public double getHeight() {
        return height;
    }

    public double getArea() {
        return 2 * (length * width + width * height + height * length);
    }

    public double getVolume() {
        return length * width * height;
    }

    public int compareTo(Object other) {
        BOX b1 = (BOX) other;
        if (this.getVolume() > b1.getVolume()) {
            return 1;
        }
        if (this.getVolume() < b1.getVolume()) {
            return -1;
        }
        return 0;
    }

    public String toString() {
        return 
        “Length:
        ”+length +
        ” Width:
        ”+width +
        ” Height:
        ”+height;
    }
} // End of BOX class
Run Code Online (Sandbox Code Playgroud)

这是我的测试课.

import java.util.*;

class ComparableTest {

    public static void main(String[] args) {
        ArrayList box = new ArrayList();
        box.add(new BOX(10, 8, 6));
        box.add(new BOX(5, 10, 5));
        box.add(new BOX(8, 8, 8));
        box.add(new BOX(10, 20, 30));
        box.add(new BOX(1, 2, 3));
        Collections.sort(box);
        Iterator itr = ar.iterator();
        while (itr.hasNext()) {
            BOX b = (BOX) itr.next();
            System.out.println(b);
        }
    }
}// End of class
Run Code Online (Sandbox Code Playgroud)

现在在课堂上ComparableTest 也不应该实现interface iterator ,我不应该定义一个interface iterator包含所有方法的内容.另外,迭代器方法的实现在哪里?

我可能很困惑,但请帮忙!谢谢.

Jon*_*eet 5

我怀疑你的意思java.util.Iterator<E>.

不,你不写:

Iterator itr= new Iterator();
Run Code Online (Sandbox Code Playgroud)

......鉴于它是一个界面,它永远不会起作用.此外,它Iterator不是iterator,你的代码应该使用import,而不是Import- Java是区分大小写的.

相反,你写道:

Iterator<Foo> iterator = list.iterator();
Run Code Online (Sandbox Code Playgroud)

但不,ComparableTest不需要实施Iterator<E>- 为什么会这样?它使用Iterator接口,但它并没有实现它.