Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning an iterator of private List (in class) considered bad practice?

Tags:

java

iterator

oop

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;
    }
}
like image 933
nmeln Avatar asked Jul 03 '15 15:07

nmeln


People also ask

Can we use iterator in list?

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.

Can an iterator be reused?

iterators are not reusable; you need to get a fresh Iterator from the Iterable collection each time you want to iterate over the elements.


1 Answers

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( ... 
like image 135
ZhongYu Avatar answered Sep 30 '22 21:09

ZhongYu