ArrayOutOfBoundsException 在 String.valueOf(int) 中是如何可能的?
2022-09-01 14:33:27
为什么此代码有时会生成 ArrayOutOfBoundsException?这怎么可能?String.valueOf(int)
public static String ipToString(ByteString bs) {
if (bs == null || bs.isEmpty()) {
return null;
} else {
StringBuilder sb = new StringBuilder();
boolean started = false;
for (Byte byt : bs) {
if (started) {
sb.append(".");
}
sb.append(String.valueOf(byt & 0xFF));
started = true;
}
return sb.toString();
}
}
java.lang.ArrayIndexOutOfBoundsException: -81914
at java.lang.Integer.getChars(Integer.java:458)
at java.lang.Integer.toString(Integer.java:402)
at java.lang.String.valueOf(String.java:3086)
at com.mystuff.mypackage.ipToString(MyCode.java:1325)
...
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
更新
当这种情况发生时,我不知道字节的值,但似乎不应该有任何可能的字节值。
一旦它发生一次,每次调用都会出错,并出现相同的异常。
环境:
java version "1.8.0_20" Java(TM) SE Runtime Environment (build 1.8.0_20-b26) Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)