当前位置: 代码迷 >> J2SE >> 关于迭代器的一个有关问题
  详细解决方案

关于迭代器的一个有关问题

热度:353   发布时间:2016-04-24 18:11:58.0
关于迭代器的一个问题
本人现在在看THINKING IN JAVA 第三版 ,看到下面的代码时遇到一个问题,代码如下
Java code
import java.util.*;public class SortedSetDemo {  //private static Test monitor = new Test();  public static void main(String[] args) {    SortedSet sortedSet = new TreeSet(Arrays.asList(    "one two three four five six seven eight".split(" ")));    System.out.println(sortedSet);    Object      low = sortedSet.first(),      high = sortedSet.last();    System.out.println(low);    System.out.println(high);    Iterator it = sortedSet.iterator();    for(int i = 0; i <= 6; i++) {       [b]  if(i == 3) low = it.next();            if(i == 6) high = it.next();         [/b]                   else it.next();    }    System.out.println(low);    System.out.println(high);    System.out.println(sortedSet.subSet(low, high));    System.out.println(sortedSet.headSet(high));    System.out.println(sortedSet.tailSet(low));    /*monitor.expect(new String[] {      "[eight, five, four, one, seven, six, three, two]",      "eight",      "two",      "one",      "two",      "[one, seven, six, three]",      "[eight, five, four, one, seven, six, three]",      "[one, seven, six, three, two]"    });*/  }} ///:~

疑问主要这两句代码的输出if(i == 3) low = it.next();
  if(i == 6) high = it.next();
,为什么输出结果是 one,two ,如果把这两行代码换一下顺序,结果又不同,是one,three,这是为什么,请分析一下

------解决方案--------------------
else匹配问题:if(i==6)在上面时,和if(i==3)匹配,故it.next执行一次
if(i==3)在上面时,和if(i==6)匹配,故it.next执行两次
  相关解决方案