How do I repeat the class of my creation in Java?

I created a class MyList that has a field

private LinkedList<User> list; 

I would like to be able to iterate over the list as follows:

 for(User user : myList) { //do something with user } 

(when my list is an instance of MyList). How? What should I add to my class?

+6
java iterator linked-list
source share
2 answers
 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(); } } 
+11
source share

Implement Iterable Interface. Here is an example on how to use this.

+5
source share

All Articles