Answer the question
In order to leave comments, you need to log in
Should I implement Iterable?
Is it good practice to implement the java.lang.Iterable interface by a class that has a collection field?
Example:
class A {
private int id;
private String name;
public A(int id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
// getters
// setters
}
class B implements Iterable<A> {
private String name;
private final List<A> list;
public B() {
list = new ArrayList<A>();
}
public void addA(A a) {
list.add(a);
}
@Override
public Iterator<A> iterator() {
return list.iterator();
}
}
// использование
B b = new B();
b.addA(new A(1, "First"));
b.addA(new A(2, "Second"));
for (A a : b) {
System.out.println(a.getName());
}
Answer the question
In order to leave comments, you need to log in
In my opinion, in this simple case, you can do with the usual getter
class B {
private String name;
private final List<A> list;
public B() {
list = new ArrayList<A>();
}
public void addA(A a) {
list.add(a);
}
public List<A> getListOfA {
return this.list;
}
}
// использование
B b = new B();
b.addA(new A(1, "First"));
b.addA(new A(2, "Second"));
for (A a : b.getListOfA()) {
System.out.println(a.getName());
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question