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)