[英]Why does AbstractStringBuilder.append behave differently for MIN_VALUE?
Consider the following methods in java.lang.AbstractStringBuilder
考虑java.lang.AbstractStringBuilder
的以下方法
Long 长
public AbstractStringBuilder append(long l) {
if (l == Long.MIN_VALUE) {
append("-9223372036854775808");
return this;
}
int appendedLength = (l < 0) ? Long.stringSize(-l) + 1
: Long.stringSize(l);
int spaceNeeded = count + appendedLength;
ensureCapacityInternal(spaceNeeded);
Long.getChars(l, spaceNeeded, value);
count = spaceNeeded;
return this;
}
Integer 整数
public AbstractStringBuilder append(int i) {
if (i == Integer.MIN_VALUE) {
append("-2147483648");
return this;
}
int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
: Integer.stringSize(i);
int spaceNeeded = count + appendedLength;
ensureCapacityInternal(spaceNeeded);
Integer.getChars(i, spaceNeeded, value);
count = spaceNeeded;
return this;
}
Why does AbstractStringBuilder#append
use a different algorithm to append the MIN_VALUE
? 为什么AbstractStringBuilder#append
使用其他算法来附加MIN_VALUE
?
因为stringSize
算法根据其输入的绝对值估计所需的字符数,除了MIN_VALUE
没有可表示的绝对值: -Integer.MIN_VALUE == Integer.MIN_VALUE
。
Because Integer.stringSize
requires a non-negative argument. 因为Integer.stringSize
需要一个非负参数。 The code looks like this: 代码如下:
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
// Requires positive x
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.