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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值