I created a class MyList that has a field
private LinkedList<User> list;
I would like to be able to iterate the list like this:
for(User user : myList) {
//do something with user
}
(when my list is an instance of MyList). How? What should I add to my class?
imort java.util.*;
class MyList implements Iterable<User> {
private LinkedList<User> list;
... // All of your methods
// And now the method that allows 'for each' loops
public Iterator<User> iterator() { return list.iterator(); }
}
Implement the Iterable interface. Here's an example on how to use this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With