Answer the question
In order to leave comments, you need to log in
When to use Collection and when to use Iterator?
In which cases should you go through the Collection, and in which cases through the Iterator? (especially if you just need to run through all the elements). Bruce Eckel in the book "Java Philosophy" (p. 354) writes that
The Iterator solution looks attractive when writing a class where the implementation of the Collection interface is difficult or impractical.
//:holding/InterfaceVsIterator.java
import typeinfo.pets.*;
import java.util.*;
public class InterfaceVsIterator{
public static void display(Iterator<Pet> it){
while(it.hasNext()){
Pet p=it.next();
System.out.print(p.id()+":"+p+"");
}
System.out.println();
}
public static void display(Collection<Pet> pets){
for(Pet p:pets)
System.out.print(p.id()+":"+p+"");
System.out.println();
}
...
InterfaceVsIterator
? Iterator
it's also an interface.
Answer the question
In order to leave comments, you need to log in
In which cases should you go through the Collection, and in which cases through the Iterator? (especially if you just need to run through all the elements).
The Iterator solution looks attractive when writing a class where the implementation of the Collection interface is difficult or impractical.
Be guided by the principle not to produce entities unnecessarily. If in the example above you just need to iterate through all the elements, then with the for each syntax, the iterator is redundant
. The class is so named because the hardest thing in programming is giving the entity the right name. Obviously, the author had not yet mastered this discipline at that time;)
in the case of an iterator:
the Iterator parameter and the input argument:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question