gpt4 book ai didi

java - 为什么 AbstractStringBuilder.append 对于 MIN_VALUE 的行为不同?

转载 作者:行者123 更新时间:2023-12-01 18:16:08 24 4
gpt4 key购买 nike

考虑java.lang.AbstractStringBuilder中的以下方法

<小时/>

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;
}

整数

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;
}
<小时/>

为什么 AbstractStringBuilder#append 使用不同的算法来附加 MIN_VALUE

最佳答案

因为stringSize算法根据其输入的绝对值来估计所需的字符数,但MIN_VALUE没有可表示的绝对值:-Integer。 MIN_VALUE == Integer.MIN_VALUE

关于java - 为什么 AbstractStringBuilder.append 对于 MIN_VALUE 的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29396411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com