You can't access a foreach
iterator variable outside of the loop since it goes out of scope. As you wrote it, the above code doesn't compile.
There's a variety of techniques that you can use, such as using the boolean
that you mentioned. You can also use a "sentinel", a dummy tab that you put at the end of tabList
that has a maximum priority that is reserved for this purpose (i.e. no "real" tab can have this priority). This guarantees that the if
condition inside the loop will be true when you reach the sentinel tab.
Finally, you can also implement your Tab
to be Comparable
, or define a separate Comparator
for it, and make tabList
an ordered collection. This way, you don't even need a sentinel, or even a foreach
loop; you can just add the newTab
to the sorted collection and have it figure out where to insert it. If tabList
is a TreeSet
, for example, the insertion will be O(log n)
. The other techniques mentioned so far is O(n)
.