TreeSet<String> sortedSet = new TreeSet<String>();
Collections.addAll(sortedSet,
"a b c d e f g h"
.split(" "));
...
Iterator<String> it = sortedSet.iterator();
for(int i = 0; i <= 6; i++) {
if(i == 3) low = it.next();
if(i == 6) high = it.next();
else it.next();
}
print(low);
print(high); //overridden
令我感到困惑的是,虽然'low'打印出“d”,但'high'打印出“h”,我认为应该是“g”。 如果我们在每次迭代中调用it.next(),第7次迭代不应该给出“g”??
答案 0 :(得分:4)
您有if
后跟if/else
。因此,i == 3
时迭代发生两次。为了清晰起见,这是您使用大括号和间距重写的原始代码:
if (i == 3) {
low = it.next();
}
if (i == 6) {
high = it.next();
} else {
it.next();
}
这会给你预期的结果:
if(i == 3) low = it.next();
else if(i == 6) high = it.next();
else it.next();