返回私有List(在类中)的迭代器被认为是不好的做法?

nme*_*eln 5 java oop iterator

假设我有两个类:Animal和Zoo,它有包含Animal实例的私有List.

我想要返回迭代器的原因是为了避免定义setter和getter以及删除方法.

这会破坏封装吗?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Zho*_*gYu 4

在 Iterable 接口之外使用 Iterator 的情况极为罕见。我建议不要这样做。

我认为这样会更好:

public Iterable<Animal> animals(){
    return Collections.unmodifiableList( animalList );
}

for(Animal a : zoo.animals()) {
    //do something
}
Run Code Online (Sandbox Code Playgroud)

我反对拥有Zoo implements Iterable<Animal>;不要引入不必要的类型关系。

在 Java 8 中,更优选的做法可能是使用 Stream 而不是 Iterable

public Stream<Animal> animals(){
    return animalList.stream();
}

zoo.animals().forEach( ... 
Run Code Online (Sandbox Code Playgroud)