如何在Java中迭代我的创作类?

sna*_*ile 6 java iterator linked-list

我创建了一个具有字段的MyList类

private LinkedList<User> list;
Run Code Online (Sandbox Code Playgroud)

我希望能够像这样迭代列表:

for(User user : myList) {
   //do something with user
}
Run Code Online (Sandbox Code Playgroud)

(当我的列表是MyList的一个实例时).怎么样?我应该在课堂上添加什么?

Ita*_*man 11

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(); }
}
Run Code Online (Sandbox Code Playgroud)


Bri*_*new 5

实现Iterable接口.这是一个如何使用它的例子.