Java 常用API 05 Math、Arrays、大数据运算

1 Math类

1)介绍

Math 类是包含用于执行基本数学运算的方法的数学工具类,如初等指数、对数、平方根和三角函数。

类似这样的工具类,其所有方法均为静态方法,并且一般不会创建对象,如System类。

2)常用方法
// 求绝对值
System.out.println(Math.abs(-5.5)); // 5.5
// 取整,向上取整
System.out.println(Math.ceil(-5.5)); // -5.0
System.out.println(Math.ceil(5.5)); // 6.0
System.out.println(Math.ceil(-5.3)); // -5.0
// 取整,向下取整
System.out.println(Math.floor(-5.3)); // -6.0
System.out.println(Math.floor(-5.5)); // -6.0
System.out.println(Math.floor(5.5)); // 5.0
// 求最大值
System.out.println(Math.max(5.5,6.7)); // 6.7
// 求最小值
System.out.println(Math.min(5.5,4.3)); // 4.3
// 求幂
System.out.println(Math.pow(5,2)); //25.0
// 取整,四舍五入
System.out.println(Math.round(5.5)); // 6
System.out.println(Math.round(5.4)); // 5
// 取随机数,[0.0,1.0)之间的double小数
System.out.println(Math.random()); 

2 Arrays类

1)介绍

此类包含用来操作数组(比如排序和搜索)的各种方法。需要注意,如果指定数组引用为null,则访问此类中的方法都会抛出空指针异常NullPointerException。

2)常用方法
// 排序
int[] arr = { 1, 4, 2, 8, 6 };
Arrays.sort(arr); // 1 2 4 6 8 

// toString方法
System.out.println(Arrays.toString(arr)); // [1, 2, 4, 6, 8]

// binarySearch,在指定的有序数组中,查找指定元素出现的位置,没有查到返回-1
System.out.println(Arrays.binarySearch(arr, 4)); // 2

3 大数据运算

1)BigInteger

Java中long型为最大整数类型,对于超过long型的数据如何去表示呢?

在Java的世界中,超过long型的整数已经不能被称为整数了,它们被封装成BigInteger对象.在BigInteger类中,实现四则运算都是方法来实现,并不是采用运算符.

//大数据封装为BigInteger对象
BigInteger big1 = new BigInteger("12345678909876543210");
BigInteger big2 = new BigInteger("98765432101234567890");
//add实现加法运算
BigInteger bigAdd = big1.add(big2);
//subtract实现减法运算
BigInteger bigSub = big1.subtract(big2);
//multiply实现乘法运算
BigInteger bigMul = big1.multiply(big2);
//divide实现除法运算
BigInteger bigDiv = big2.divide(big1);
2)BigDecimal

double和float类型在运算中很容易丢失精度,造成数据的不准确性,Java提供我们BigDecimal类可以实现浮点数据的高精度运算。

 //大数据封装为BigDecimal对象
BigDecimal big1 = new BigDecimal("0.09");
BigDecimal big2 = new BigDecimal("0.01");
//add实现加法运算
BigDecimal bigAdd = big1.add(big2);

BigDecimal big3 = new BigDecimal("1.0");
BigDecimal big4 = new BigDecimal("0.32");
//subtract实现减法运算
BigDecimal bigSub = big3.subtract(big4);

BigDecimal big5 = new BigDecimal("1.105");
BigDecimal big6 = new BigDecimal("100");
//multiply实现乘法运算
BigDecimal bigMul = big5.multiply(big6);

猜你喜欢

转载自blog.csdn.net/lihaogn/article/details/81017066