0

如果我创建一个新对象,程序运行正常:

Iterator iter = Students.iterator();
    while (iter.hasNext()){
        Student newstudent=(Student) iter.next();
        if (newstudent.getCourse()==2){
            System.out.println(  newstudent.getName());}

但如果不喜欢:

Iterator iter = Students.iterator();
  while (iter.hasNext()){
   if (((Student) iter.next()).getCourse()==2){
     System.out.println(( (Student)iter.next()).getName());}//Here it is printing out the next object afther that I have checked

如何坚持同一个对象?

4

7 回答 7

1

暂时保存当前学生:

Iterator iter = Students.iterator();
while (iter.hasNext()){
  Student currentStudent = (Student) iter.next()
  if (currentStudent.getCourse()==2) {
    System.out.println(currentStudent.getName());
  } //Here it is printing
}
于 2013-08-14T10:03:56.727 回答
0
   if (((Student) iter.next()).getCourse()==2){ //first time next happened
         System.out.println(( (Student)iter.next()).getName());}/  after condition next happened again

简而言之,您正在检查条件并在(N.next)上N 打印值。N+1

你在第一种方法中所做的都是正确的。

于 2013-08-14T10:06:32.790 回答
0

您在程序中调用了 iter.next() 两次。因此错误!

于 2013-08-14T10:10:34.857 回答
0

如果您不想推进迭代器,您总是可以考虑使用 a PeekingIterator,它允许您peek在不删除它的情况下处理下一个元素,例如:

final Iterator<Student> iter = Iterators.peekingIterator(Students.iterator());

final Student a = iter.peek();
final Student b = iter.peek();
final Student c = iter.next();

assert a == b == c;

PeekingIterator包含在Google的Guava 库中,虽然它很容易推出你自己的。

于 2013-08-14T10:45:13.500 回答
0

您只需要调用next()一次方法

 while (iter.hasNext()){
 Student student =  (Student) iter.next();
  if (student.getCourse()==2){
     System.out.println(( student.getName());
}
于 2013-08-14T10:04:51.813 回答
0

因为在以后的情况下,您要调用iterator.next()两次。该next()调用返回迭代器指向的当前元素并将光标移动下一个元素。所以在你的情况下

Iterator iter = Students.iterator();
while (iter.hasNext()){
   if (((Student) iter.next()).getCourse()==2){ //--> Student 1 is returned by next() call and iterator points to Student 2 (next in the list)
     System.out.println(( (Student)iter.next()).getName());} //--> Student 2 is returned by next() call

iterator.next()像在第一个示例中所做的那样,存储循环开头返回的元素是一种很好的做法,以避免出现意外行为

于 2013-08-14T10:02:45.793 回答
0

每当您调用iter.next()迭代器的当前索引时,它就会向前移动。因此需要将当前Student对象保存在临时对象中。
最初
-|
[-][-][-][-]
iter.next()
---|
[-][-][-][-]

如果你iter.next()从这里调用 twise
---------|
[-][-][-][-]


考虑每个 [-] 是学生对象

于 2013-08-14T10:04:23.973 回答