简体   繁体   English

为什么AbstractStringBuilder.append的行为与MIN_VALUE不同?

[英]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.

相关问题 为什么Integer class中的MIN_VALUE和MAX_VALUE定义为@native? - Why MIN_VALUE and MAX_VALUE in Integer class is defined @native? 重现行为MAX_VALUE和MIN_VALUE - Reproduce behavior MAX_VALUE and MIN_VALUE java Integer.MAX_VALUE, MIN_VALUE 溢出 - java Integer.MAX_VALUE, MIN_VALUE overflow 为什么\ R在Java 8和Java 9之间的正则表达式中表现不同? - Why does \R behave differently in regular expressions between Java 8 and Java 9? 为什么 Path.relativize 在 Java 8 和 Java 11 上表现不同? - Why does Path.relativize behave differently on Java 8 and Java 11? 为什么 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 上的“关闭”调用在 C# 和 Java 中表现不同? - Why does the “Close” call on a stream behave differently in C# and in Java? 为什么proguard -keepclassmembers基于类说明符的行为不同? - Why does proguard -keepclassmembers behave differently based on class-specifier? 为什么我的文本规范化在不同环境中的行为会有所不同? - Why does my text normalization behave differently in different environments? 为什么String.getBytes()在已编译的jar中表现不同? - Why does String.getBytes() behave differently in a compiled jar? 为什么使用Swing绘制在Java 8和Java 6中的表现不同? - Why does painting with Swing behave differently in Java 8 and Java 6?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM