java
runtime_error
ai_generated
true
java.lang.NegativeArraySizeException
ID: java/negative-array-size
87%Fix Rate
81%Confidence
1Evidence
2024-06-12First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Java 8 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
Root Cause
Thrown when an array is created with a negative size, usually due to an integer overflow or a bug in array size calculation.
generic中文
当使用负数大小创建数组时抛出,通常是由于整数溢出或数组大小计算错误。
Official Documentation
https://docs.oracle.com/javase/8/docs/api/java/lang/NegativeArraySizeException.htmlWorkarounds
-
95% success Validate the array size before creation: `if (size < 0) throw new IllegalArgumentException("Size must be non-negative: " + size);`.
Validate the array size before creation: `if (size < 0) throw new IllegalArgumentException("Size must be non-negative: " + size);`. -
90% success Use long arithmetic for size calculation to prevent integer overflow: `long safeSize = (long) a * b; if (safeSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Size too large");`.
Use long arithmetic for size calculation to prevent integer overflow: `long safeSize = (long) a * b; if (safeSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Size too large");`. -
85% success Add a guard clause: `int size = computeSize(); if (size < 0) { size = 0; }` to handle edge cases gracefully.
Add a guard clause: `int size = computeSize(); if (size < 0) { size = 0; }` to handle edge cases gracefully.
中文步骤
Validate the array size before creation: `if (size < 0) throw new IllegalArgumentException("Size must be non-negative: " + size);`.Use long arithmetic for size calculation to prevent integer overflow: `long safeSize = (long) a * b; if (safeSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Size too large");`.Add a guard clause: `int size = computeSize(); if (size < 0) { size = 0; }` to handle edge cases gracefully.
Dead Ends
Common approaches that don't work:
-
95% fail
The root cause (negative size) is not fixed; retrying will throw the same exception.
-
70% fail
This masks the underlying bug and may lead to incorrect program behavior or data loss.
-
80% fail
If the size is Integer.MIN_VALUE, Math.abs() returns a negative value due to overflow, still causing the exception.