Java中的goto

goto是java中的保留字,确不是java中的关键字,这一点很多人都知道,为什么不用goto是因为对大多数人而言,用好goto很难,如果使用不当,会使代码的逻辑变得很混乱,故在java中未明确使用goto关键字,主要是希望开发人员能够谨慎使用。但同时,在java中,goto完全可以通过带标签的continuebreak关键字实现。

虽然没有goto关键字,但在使用到goto的场景还是非常丰富的,譬如在java.util.Collections中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
}

在获取List中子List所在的起始位置时,其中使用到的continue加label的方式,能够通过更简洁的代码以实现。