Reading Containers in Depth chapter from the Thinking In Java book. Saw this example(modified from SortedMapDemo.java):
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
What baffles me is that while 'low' prints out "d", 'high' prints out "h", for which I think should be "g" instead.
If we're calling it.next() in each iteration, shouldn't the 7th iteration gives "g"??
You have an if
followed by an if/else
. So the iteration occurs twice when i == 3
. Here is your original code re-written with braces and spacing for clarity:
if (i == 3) {
low = it.next();
}
if (i == 6) {
high = it.next();
} else {
it.next();
}
This would give you expected results:
if(i == 3) low = it.next();
else if(i == 6) high = it.next();
else it.next();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.