Java8 math新方法

*exact() 方法
首先看一组扩展已经存在的常用算术操作方法,从名称及可以知其意,处理实现原有功能外,还增加了当结果溢出时抛出异常。这些方法可以使用integer和long类型作为参数。

addExact()
返回两个参数之和,结果溢出时抛出ArithmeticException 异常:

Math.addExact(100, 50);               // returns 150
Math.addExact(Integer.MAX_VALUE, 1);  // throws ArithmeticException
1
2
substractExact()方法
返回两个参数之差,结果溢出时抛出ArithmeticException 异常:

Math.subtractExact(100, 50);           // returns 50
Math.subtractExact(Long.MIN_VALUE, 1); // throws ArithmeticException
1
2
incrementExact()方法
返回参数值加一,结果溢出时抛出ArithmeticException 异常:

Math.incrementExact(100);               // returns 101
Math.incrementExact(Integer.MAX_VALUE); // throws ArithmeticException
1
2
decrementExact()方法
返回参数值减一,结果溢出时抛出ArithmeticException 异常:

Math.decrementExact(100);            // returns 99
Math.decrementExact(Long.MIN_VALUE); // throws ArithmeticException
1
2
multiplyExact()方法
返回两个参数之积,结果溢出时抛出ArithmeticException 异常:

Math.multiplyExact(100, 5);            // returns 500
Math.multiplyExact(Long.MAX_VALUE, 2); // throws ArithmeticException
1
2
negateExact()方法
改变参数符号,结果溢出时抛出ArithmeticException 异常。我们来看看值在内存中的表示,并理解为什么会溢出,因为并不像其他exact方法那么直观看出来:

Math.negateExact(100);               // returns -100
Math.negateExact(Integer.MIN_VALUE); // throws ArithmeticException
1
2
第二个示例需要解释下,因为不能一眼看出来:溢出是因为Integer.MIN_VALUE 是 −2.147.483.648,而Integer.MAX_VALUE 是 2.147.483.647,所以返回值超出整数范围。

其他方法
floorDiv()
第一个参数除以第二参数,然后针对结果执行floor操作,返回小于或等于商的整数:

Math.floorDiv(7, 2));  // returns 3
1
商为 3.5 ,所以 floor(3.5) == 3.

让我们看另一个示例:

Math.floorDiv(-7, 2)); // returns -4
1
商为-3.5 ,所以 floor(-3.5) == -4.

modDiv()方法
该方法与前面floorDiv()方法类似, 但在模数或余数上应用floor() 操作,而不是商:

Math.modDiv(5, 3));  // returns 2
1
我们看到 , modDiv() 方法两个参数为正数,和 % 操作符效果一样。让看看另一个不同示例:

Math.modDiv(-5, 3));  // returns 1
1
结果为 1 而不是 2 ,因为floorDiv(-5, 3) 是 -2 ,而不是 -1.

nextDown()方法
返回参数直接较低的值(支持 float 或 double 参数):

float f = Math.nextDown(3);  // returns 2.9999998
double d = Math.nextDown(3); // returns 2.999999761581421
--------------------- 
作者:neweastsun 
来源:CSDN 
原文:https://blog.csdn.net/neweastsun/article/details/79873698 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值