您的位置:首页 > 其它

BigInteger详解

2016-09-13 08:39 459 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  源码分析