public class InfiniteLoopTrap {
public static void main(String[] args) {
int end = Integer.MAX_VALUE; // 2,147,483,647
int start = end - 50; // 2,147,483,597
int count = 0;
for (int i = start; i <= end; i++) { // 陷阱在這裡!
count++;
System.out.println("第 " + count + " 次迴圈");
}
}
}
i 從 start 遞增到 end (Integer.MAX_VALUE) 正常執行 51 次。i == Integer.MAX_VALUE 迴圈體執行完,執行 i++。Integer.MAX_VALUE + 1 發生**整數溢位**,變為 Integer.MIN_VALUE (-2,147,483,648)。i <= end 即 -2147483648 <= 2147483647 為 true。i 從負數遞增回正數,永不超過 end,**無限迴圈**。// 方式 1:使用 < 而非 <= (前提 end 不為 MAX_VALUE)
for (int i = start; i < end; i++) { ... }
// 方式 2:使用 long 避免溢位
for (long i = start; i <= end; i++) { ... }
// 方式 3:計算次數迴圈
int iterations = end - start + 1; // 注意溢位,若範圍大用 long
for (int i = 0; i < iterations; i++) {
int current = start + i;
...
}
// 方式 4:Java 8+ IntStream (自動處理邊界)
IntStream.rangeClosed(start, end).forEach(i -> { ... });
// 或
IntStream.iterate(start, i -> i + 1).limit(iterations).forEach(...);
Integer.MAX_VALUE, Long.MAX_VALUE 邊界。long end = Long.MAX_VALUE;
for (long i = end - 2; i <= end; i++) { ... } // 同樣會溢位無限迴圈
這個陷阱生動展示了「邊界條件思維」的重要性。寫迴圈時,請問自己:索引變數會不會溢位?邊界值是否為型別極值?。善用 IntStream、for (int i=0; i