Java8Math新增方法

star2017 1年前 ⋅ 1800 阅读

引用至:https://blog.csdn.net/neweastsun/article/details/79873698

java8 Math新增方法

通常都认为java8新功能主要包括函数式编程及lambda表达式。然而,除了那些大的特点之外,还有其他的,影响力小却很有趣,大多时候不为人所知,甚至不太被人评论。
本文我们列举java.lang.Math类中新增的方法,并给一些小的示例来说明。

*exact() 方法

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

addExact()

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

Math.addExact(100, 50);               // returns 150
Math.addExact(Integer.MAX_VALUE, 1);  // throws ArithmeticException12

substractExact()方法

返回两个参数之差,结果溢出时抛出ArithmeticException 异常:

Math.subtractExact(100, 50);           // returns 50
Math.subtractExact(Long.MIN_VALUE, 1); // throws ArithmeticException12

incrementExact()方法

返回参数值加一,结果溢出时抛出ArithmeticException 异常:

Math.incrementExact(100);               // returns 101
Math.incrementExact(Integer.MAX_VALUE); // throws ArithmeticException12

decrementExact()方法

返回参数值减一,结果溢出时抛出ArithmeticException 异常:

Math.decrementExact(100);            // returns 99
Math.decrementExact(Long.MIN_VALUE); // throws ArithmeticException12

multiplyExact()方法

返回两个参数之积,结果溢出时抛出ArithmeticException 异常:

Math.multiplyExact(100, 5);            // returns 500
Math.multiplyExact(Long.MAX_VALUE, 2); // throws ArithmeticException12

negateExact()方法

改变参数符号,结果溢出时抛出ArithmeticException 异常。我们来看看值在内存中的表示,并理解为什么会溢出,因为并不像其他exact方法那么直观看出来:

Math.negateExact(100);               // returns -100
Math.negateExact(Integer.MIN_VALUE); // throws ArithmeticException12

第二个示例需要解释下,因为不能一眼看出来:溢出是因为Integer.MIN_VALUE 是 −2.147.483.648,而Integer.MAX_VALUE 是 2.147.483.647,所以返回值超出整数范围。

其他方法

floorDiv()

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

Math.floorDiv(7, 2));  // returns 31

商为 3.5 ,所以 floor(3.5) == 3.

让我们看另一个示例:

Math.floorDiv(-7, 2)); // returns -41

商为-3.5 ,所以 floor(-3.5) == -4.

modDiv()方法

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

Math.modDiv(5, 3)); // returns 21

我们看到 , modDiv() 方法两个参数为正数,和 % 操作符效果一样。让看看另一个不同示例:

Math.modDiv(-5, 3));  // returns 11

结果为 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.99999976158142112

总结

我们描述了java8中java.lang.Math类中所有新的方法,并通过示例给与解释说明。

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: