2013/05/02

[java] Integer 中 valueOf 與 parseInt 的不同

兩個方法的功能皆是將 String 轉成 Integer 及 int,不同的是回傳的型態,valueOf 是回傳 IntegerparseInt 是回傳 int
valueOf 中,其內部依然是呼叫 parseInt,但是它會有一個 cache,儲存 -128 ~ 127 的 Integer,如果要回傳的結果落在 -128 ~ 127 的範圍中,就回傳 cache 中的 Integer,所以用 == 來判斷,結果會是 true,這樣的暫存機制是屬於 immutable object,對垃圾回收來說是有利的。
public class Test { 
    public static void main(String[] args) {
        Integer a = Integer.valueOf("52");
        Integer b = Integer.valueOf("52");
        Integer c = Integer.valueOf("520");
        Integer d = Integer.valueOf("520");

        System.out.println("Is instance the same? " + (a == b)); // true
        System.out.println("Is instance the same? " + (c == d)); // false
    }
}
查查 valueOf 的原始碼,先透過 parseInt 轉成 int 後,送到 valueOf(int i)IntegerCache 是 private static class,其中 low 與 high 就是設定 cache 的範圍。
public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        ....
        high = h;
    }
}

原文網址
http://javarevisited.blogspot.tw/2013/04/difference-between-valueof-and-parseint-method-java.html

沒有留言:

張貼留言