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);
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值