有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

接口Iterator是否已经在java库中的某个地方定义过(注意术语)。 i、 e

我想问的是,假设我有一个arraylist,现在我写

Iterator itr= new Iterator();

但我从来没有定义过这样的事情

public interface Iterator{  // all the methods };

我需要导入一些已经定义了迭代器的包吗

让我举个例子:

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

这是我的测试课

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

现在在类ComparableTest中,它不应该实现interface iterator吗?我不应该定义一个包含所有方法的interface iterator。此外,迭代器方法的实现在哪里

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


共 (4) 个答案

  1. # 1 楼答案

    当然,它已经被定义了。它是包java.util中的内置接口,您需要像java.util.Iterator一样导入它

  2. # 2 楼答案

    接口Iterator在标准API的包java.util中定义。可以使用它,因为代码中有import java.util.*;

    你不必实施它;它由方法ArrayList.iterator()返回的内部类ArrayList实现

    您可以通过查看标准API的源代码来了解类似的情况,该API随JDK附带在一个文件src中。拉链

  3. # 3 楼答案

    我猜你的意思是^{}

    不,你不会写:

    Iterator itr= new Iterator();
    

    。。。考虑到这是一个接口,这永远不会起作用。另外,它是Iterator,而不是iterator,您的代码应该使用import,而不是Import——Java区分大小写

    相反,你写:

    Iterator<Foo> iterator = list.iterator();
    

    但是不,ComparableTest不需要实现Iterator<E>——为什么要实现呢?它使用接口Iterator,但它不实现

  4. # 4 楼答案

    除了前面的文章,考虑到当前的上下文,没有必要使用迭代器。相反,您应该尝试java的“增强for循环”:

    for(BOX temp: box){
        //do something...
    }