Is the interface Iterator already defined somewhere in java library (mind the terminology).
i.e.
What i am asking is that, say i have an arraylist, now i write.
Iterator itr= new Iterator();
but i never define anything like
public interface Iterator{ // all the methods };
Do i need to import some package where this iterator is already defined?
Let me take an example here:
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
And here is my test 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
Now in class ComparableTest should not it implement interface iterator also, shall i not define an interface iterator that will contain all the methods. Also, where is the implementation of the iterator methods are?
I maybe confused alot, but kindly help!
thanks.
I suspect you mean
java.util.Iterator<E>.And no, you don’t write:
… that could never work, given that it’s an interface. Also, it’s
Iterator, notiterator, and your code should useimport, notImport– Java is case-sensitive.Instead, you write:
But no,
ComparableTestdoesn’t need to implementIterator<E>– why would it? It uses theIteratorinterface, but it doesn’t implement it.