2015-04-01 52 views
0

考慮java.lang.AbstractStringBuilder爲什麼AbstractStringBuilder.append對於MIN_VALUE的行爲不同?


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

+0

你是說爲什麼兩個'MIN_VALUE's都是特殊的? – dhke 2015-04-01 16:53:00

回答

1

因爲Integer.stringSize需要一個非負面的參數。代碼如下所示:

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

由於stringSize算法估計從其輸入的絕對值所需的字符數,除了MIN_VALUE沒有可表示的絕對值:-Integer.MIN_VALUE == Integer.MIN_VALUE

相關問題