N
N
nlog2015-02-26 10:15:10
Java
nlog, 2015-02-26 10:15:10

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());
}

In this case, users of class B do not have the ability to directly interact with its internal list A. However, in this case, class B ceases to be a POJO, and its use in JSP, ORM, etc. will be in question.
In what cases is the implementation of java.lang.Iterable acceptable, and in what cases it is better to refuse it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
asd111, 2015-02-26
@asd111

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 question

Ask a Question

731 491 924 answers to any question