I am going to have a class that has a ArrayList people field I want clients of this class to be able to iterate over those objects. How do I do this? Do I just return people.iterator(); ?
for example, in the client I want to be able to do this:
for( Person p : people ) {
// do something
}
Is this what I need in my class?
public class People implements Iterable<Person> {
private ArrayList<Person> people;
@Override
public Iterator<Person> iterator() {
// TODO Auto-generated method stub
return people.iterator();
}
If you want to prevent modification to the list itself via the iterator, just delegate iterator()
to an unmodifiable list like this:
public class People implements Iterable<Person> {
private ArrayList<Person> people;
@Override
public Iterator<Person> iterator() {
return Collections.unmodifiableList(people).iterator();
}
}
Otherwise, what you have is fine.
Note, however, that unless Person
is immutable, there is nothing you can do to prevent a caller from modifying the Person
objects themselves. If that's OK, then no big deal. If that's a problem, then you could create a deep copy of people
and return an iterator to that.
If you want the returned iterator to reflect modifications to the Person
s but not to allow changing of the Person
s, or if a deep copy is too expensive or unnecessary, you could create an ImmutablePerson
that extends Person
and wraps a Person
but does not allow modification via setters, and return a list of those wrapped around the actual Person
objects.
Yes. The enhanced for loop requires an array or Iterable
. Iterable
is required to have iterator(
that returns a reasonable iterator that has useful meaning in regard to your data.
You can now use the enhanced for loop and it is somewhat semantically correct. However, Iterator
provides remove(
so anyone using your iterator can remove things from your people list, which may not be what you want. Perhaps using new ArrayList(people).iterator()
or Collctions.unmodifiableList(people).iterator()
can work as you copy the list and get the iterator for it .
You can also provide getPeople
by creating a getter that creates an ImmutableList
or just a copy of your internal arrayList.
On another note, why not extend ArrayList if you need extra functionality? I haven't seen exactly what you're doing with it so I can only guess.
Simply provide a getter for your People list:
public ArrayList<Person> get getPeople() {
return people;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.