黑马程序员技术交流社区

标题: 迭代器问题 [打印本页]

作者: wodeairenw    时间: 2013-4-23 16:55
标题: 迭代器问题
本帖最后由 wodeairenw 于 2013-4-23 19:36 编辑

public class Test
{
public static void main(String[] args)
{
  List<Integer> memory= new ArrayList<Integer>();
  for(int i=1;i<=100;i++)
  {
   
   memory.add(i);
   System.out.println("i="+i);
  }
  Iterator<Integer> it = memory.iterator();
  while(it.hasNext())
  {
   it.next();
   System.out.println("迭代i="+it.next());
  }
  
}
}
打印出来的结果,为什么迭代器是2,4,6.。。。中间会隔一个数?这是为什么?
作者: 郭登旭    时间: 2013-4-23 17:01
while(it.hasNext())
  {
   it.next();        //这里取到的是1,但没有输出
   System.out.println("迭代i="+it.next());    //这里取到的是2,输出2
  }
每次it.next();指针移到一位,如果想都输出,应该这样
while(it.hasNext())
  {
   System.out.println("迭代i="+it.next());
  }
作者: 尹丽峰    时间: 2013-4-23 17:02
本帖最后由 尹丽峰 于 2013-4-23 17:04 编辑
  1. public class diedaiqi
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.           List<Integer> memory= new ArrayList<Integer>();
  6.           for(int i=1;i<=100;i++)
  7.           {
  8.            
  9.            memory.add(i);
  10.            System.out.println("i="+i);
  11.           }
  12.           Iterator<Integer> it = memory.iterator();
  13.           while(it.hasNext())
  14.           {
  15.           // it.next();去掉这,你sop下面又执行一次
  16.            System.out.println("迭代i="+it.next());
  17.           }
  18.          
  19.         }

  20. }
复制代码

作者: wodeairenw    时间: 2013-4-23 17:03
郭登旭 发表于 2013-4-23 17:01
while(it.hasNext())
  {
   it.next();        //这里取到的是1,但没有输出

谢谢,也就是说调用了两次返回方法。知道了
作者: lipingan0520    时间: 2013-4-23 18:04
  1. while(it.hasNext())
  2.   {
  3.     it.next();
  4.     System.out.println("迭代i="+it.next());
  5.   }
复制代码
每个it.next()就取出一次
你取了2次,一次没输出,一次输出了,所以就看到了只有2 4 6 8这些了。
最好每判断一次就输出一次。
作者: 山西_李帅    时间: 2013-4-23 18:21
因为你已经it.next()迭代过一次了,而且也没有输出。所以你看到的是246...




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2