3.9 大数值
如果基本的整数和浮点数精度不能够满足需求,那么可以使用java.math包中的两个很有用的类:BigInteger和BigDecimal。这两个类可以处理包含任意长度数字序列的数值BigInteger类实现了任意精度的整数运算,BigDecimal实现了任意精度的浮点数运算。
使用静态的valuesOf方法可以将普通的数值转换为大数值:
BigInteger a = BigInteger.valuesOf(100);
遗憾的是,不能使用人们熟悉的算术运算符处理大数值。而需要使用大数值类中的add和multiply方法。
BigInteger c = a.add(b); // c = a+b
BigInteger d = c.multiply(b.add(BigInteger.valuesOf(2)));// d = c* (b+2)
方法 | 解释 |
---|---|
BigInteger add(BigInteger other) | |
BigInteger subtract(BigInteger other) | |
BigInteger multiply(BigInteger other) | |
BigInteger divide(BigInteger other) | |
BigInteger mod(BigInteger other) | 返回这个大整数和另外一个大整数other的和、差、积、商以及余数 |
int compareTo(BigInteger other) | 如果这个大整数与另外一个大整数other相等,返回0;如果这个大整数小于另一个大整数other,返回负数;否则,返回正数。 |
static BigInteger valuesOf(long x) | 返回值等于x的大整数 |
3.10.5 数组排序
Arrays API
方法 | 解释 |
---|---|
static String toString(type[] a) | 返回包含a中数组元素的字符串,这些元素将被放在括号内并用,分割 |
static type copyOf(type[] a,int length) | |
static type copyOf(type[] a,int start,int end) | 返回与a类型相同的一个数组,其长度为length或者end-start,数组元素为a的值。 |
static void sort(type[] a) | 采用优化的快速排序算法对数组进行排序 |
static int binarySearch(type[] a,type v) | |
static int binarySearch(type[] a,int start,int end,type v) | 采用二分搜索算法查找值V,如果查找成功,则返回值相应的下标值;否则,返回一个负数。 |
static void fill(type[] a,type v) | 将数组所有元素值设置成V |
static boolean equals(type[] a,type[] b) | 如果俩数组大小相同,并且下标相同的元素对应相等,返回true |