BigInteger詳解

BigInteger:Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java.lang.Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.(BigInteger是個不可變的任意精度的整數類型,對java的基本類型integer的所有操作都進行了模擬實現,還支持很多額外的方法,例如gcd的計算,質數測試等等)

1、BigInteger的創建:其構造方法私有,0、1、10可以直接通過BigInteger.ZERO、BigInteger.ONE、BigInteger.TEN獲得,其它的值可以通過BigInteger.valueOf(int value)來創建。

再來細看一下valueOf:

    public static BigInteger valueOf(long val) {
        // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
        if (val == 0)
            return ZERO;
        if (val > 0 && val <= MAX_CONSTANT)
            return posConst[(int) val];
        else if (val < 0 && val >= -MAX_CONSTANT)
            return negConst[(int) -val];

        return new BigInteger(val);
    }
    /**
     * Initialize static constant array when class is loaded.
     */
    private final static int MAX_CONSTANT = 16;
    private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
    private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];

從上面的代碼中可以看出BigInteger對-16至-1和1至16這32個值進行了緩存。


然後,又沒啥寫得了。。。

對於那些“修改”BigInteger的方法,如add(),sub()之類。一定要記住BigInteger是一個immutable type。immutable type。immutable type。。。

所以一定要用一個BigInteger引用來保存其“修改”方法所返回的“修改”後的BigInteger。否則你就白“修改”了。。。

注意上面的修改2字都加了“”,因爲其並沒有修改。僅僅是創建了一個新的BigInteger儲存計算後的值,並返回該BigInteger


發佈了59 篇原創文章 · 獲贊 26 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章