Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate a 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 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?

like image 932
snakile Avatar asked Jan 09 '10 12:01

snakile


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(); }
}
like image 191
Itay Maman Avatar answered Oct 23 '22 02:10

Itay Maman


Implement the Iterable interface. Here's an example on how to use this.

like image 30
Brian Agnew Avatar answered Oct 23 '22 03:10

Brian Agnew