Java 8 数学新方法
1. 简介
通常,当我们想到 Java 8 版附带的新特性时,首先想到的是函数式编程和 lambda 表达式。 然而,除了这些大功能之外,还有其他一些功能,可能影响较小,但也很有趣,而且很多时候并不为人所知,甚至没有被任何评论涵盖。 在本教程中,我们将列举并举例说明添加到该语言的核心类之一的每个新方法:java.lang.Math 。
2. 新的*exact()*方法
首先,我们有一组新方法可以扩展一些现有的和最常见的算术运算。 正如我们将看到的,它们是非常不言自明的,因为它们具有与派生方法完全相同的功能,但添加了抛出异常以防万一,结果值溢出其类型的最大值或最小值.
我们可以使用Integer和Long整数作为参数的这些方法。
2.1.addExact()
添加两个参数,在添加的溢出(适用于所有Exact()方法)的情况下抛出ArithmeticException:
Math.addExact(100, 50); // returns 150
Math.addExact(Integer.MAX_VALUE, 1); // throws ArithmeticException
2.2. subtractExact()
从第一个参数中减去第二个参数的值,在减法溢出的情况下抛出ArithmeticException :
Math.subtractExact(100, 50); // returns 50
Math.subtractExact(Long.MIN_VALUE, 1); // throws ArithmeticException
2.3. incrementExact()
将参数加一,在溢出的情况下抛出ArithmeticException:
Math.incrementExact(100); // returns 101
Math.incrementExact(Integer.MAX_VALUE); // throws ArithmeticException
2.4. decrementExact()
将参数减一,在溢出的情况下抛出ArithmeticException:
Math.decrementExact(100); // returns 99
Math.decrementExact(Long.MIN_VALUE); // throws ArithmeticException
2.5. multiplyExact()
将两个参数相乘,在乘积溢出的情况下抛出ArithmeticException:
Math.multiplyExact(100, 5); // returns 500
Math.multiplyExact(Long.MAX_VALUE, 2); // throws ArithmeticException
2.6. negateExact()
更改参数的符号,在溢出的情况下抛出ArithmeticException。 在这种情况下,我们必须考虑内存中值的内部表示来理解为什么会出现溢出,因为它不像其他“精确”方法那样直观:
Math.negateExact(100); // returns -100
Math.negateExact(Integer.MIN_VALUE); // throws ArithmeticException
第二个示例需要解释,因为它并不明显:溢出是由于Integer.MIN_VALUE为 -2.147.483.648,而另一方面Integer.MAX_VALUE为 2.147.483.647,因此返回的值不适合Integer以一个单位。
3. 其他方法
3.1. floorDiv()
将第一个参数除以第二个参数,然后对结果执行floor()操作,返回小于或等于商的Integer:
Math.floorDiv(7, 2)); // returns 3
确切的商是 3.5,所以floor(3.5) == 3。 让我们看另一个例子:
Math.floorDiv(-7, 2)); // returns -4
确切的商是 -3.5 所以floor(-3.5) == -4。
3.2. modDiv()
这类似于前面的方法floorDiv(),但将*floor()*运算应用于除法的模数或余数而不是商:
Math.modDiv(5, 3)); // returns 2
正如我们所见,**两个正数的*modDiv()***与 % operator 相同。让我们看一个不同的例子:
Math.modDiv(-5, 3)); // returns 1
它返回 1 而不是 2,因为*floorDiv(-5, 3)*是 -2 而不是 -1。
3.3. nextDown()
返回参数的立即较低的值(支持float或double参数):
float f = Math.nextDown(3); // returns 2.9999998
double d = Math.nextDown(3); // returns 2.999999761581421