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

www.MyException.Cn  网友分享于：2013-01-31  浏览：3次

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 == 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执行两次