Suppose I have two classes: Animal and Zoo, which has private List containing instances of Animal.
Reason why I want to return iterator is to avoid defining setters and getters and removal methods.
Does that break encapsulation?
class Zoo{
private List<Animal> animalList;
public Zoo(){
animalList = new ArrayList<Animal>();
}
public void addAnimal(Animal animal){
animalList.add(animal);
}
public Iterator<Animal> iterator(){
return animalList.iterator();
}
}
class Animal{
private String name;
private double weight, height;
Animal(String name, double weight, double height){
this.name = name;
this.weight = weight;
this.height = height;
}
}
An iterator is an object in Java that allows iterating over elements of a collection. Each element in the list can be accessed using iterator with a while loop.
iterators are not reusable; you need to get a fresh Iterator from the Iterable collection each time you want to iterate over the elements.
It is extremely uncommon to use Iterator outside an Iterable interface. I'd advise against such practice.
I think this would be better:
public Iterable<Animal> animals(){
return Collections.unmodifiableList( animalList );
}
for(Animal a : zoo.animals()) {
//do something
}
I'm against having Zoo implements Iterable<Animal>
; don't introduce unnecessary type relations.
In Java 8, a more preferred practice is probably to use Stream instead of Iterable
public Stream<Animal> animals(){
return animalList.stream();
}
zoo.animals().forEach( ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With