1

I came across this code in Java API Collection class. Does it work like switch statement ? How is this idiom called ?

public static int indexOfSubList(List<?> source, List<?> target) { int sourceSize = source.size(); int targetSize = target.size(); int maxCandidate = sourceSize - targetSize; if (sourceSize < INDEXOFSUBLIST_THRESHOLD || (source instanceof RandomAccess&&target instanceof RandomAccess)) { nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { for (int i=0, j=candidate; i<targetSize; i++, j++) if (!eq(target.get(i), source.get(j))) continue nextCand; // Element mismatch, try next cand return candidate; // All elements of candidate matched target } } else { // Iterator version of above algorithm ListIterator<?> si = source.listIterator(); nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { ListIterator<?> ti = target.listIterator(); for (int i=0; i<targetSize; i++) { if (!eq(ti.next(), si.next())) { // Back up source iterator to next candidate for (int j=0; j<i; j++) si.previous(); continue nextCand; } } return candidate; } } return -1; // No candidate matched the target } 
3
  • 2
    Does what work like switch? You've presented a lot of code. Are you really just interested in the labeled continue statements? Commented Jan 4, 2013 at 13:56
  • Yes I was, I just saw it for the first time. Commented Jan 4, 2013 at 13:58
  • @JonSkeet I think he is referring to labels and labelled continues Commented Jan 4, 2013 at 13:58

2 Answers 2

5

No, its just a labeled break/continue. see here:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Java allows using label as break/continue targets. By default a break/continue will affect the inner-most loop its in, but using labels you can break out of outer loops.

Sign up to request clarification or add additional context in comments.

3 Comments

its rarely useful, and makes some people cross themselves and call you the devil for using gotos :-)
In 25 years of programming I have used a label (in C) once. Never needed it yet in Java (in 15 years)! Try to avoid it if possible.
i used it for the 1st time about 2 weeks after taking up java and got into a heated argument with my then-team-lead. if you really need to break/continue out of an inner loop, say 3+ loops deep it both perfors better and looks better (the aternative involves a boolean flag and a lot of noise checking it). of course if you have 3+ loops one inside the other there's probably something else wrong with your code ...
1

Assuming you're referring to nextCand: and continue nextCand;, it's simply a way to continue to the next iteration of the outer loop from within the inner loop.

A simple continue would continue the inner loop instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.