Java 8 Mathの新しいメソッド

Java 8 Mathの新しいメソッド

1. 前書き

通常、Javaのバージョン8に付属する新機能について考えるとき、関数型プログラミングとラムダ式が最初に頭に浮かぶものです。

それでも、これらの大きな機能の他に、影響は小さいかもしれませんが、興味深いものであり、多くの場合、あまり知られていないか、レビューでカバーされていないものもあります。

このチュートリアルでは、言語のコアクラスの1つであるjava.lang.Mathに追加された新しい各メソッドの例を列挙して示します。

2. 新しい*exact()メソッド

まず、既存の最も一般的な算術演算の一部を拡張する新しいメソッドのグループがあります。

後で説明するように、これらは派生したメソッドとまったく同じ機能を備えていますが、the addition of throwing an exception in case, the resulting value overflows the max or min values of their types.を使用しているため、非常にわかりやすくなっています。

これらのメソッドは、integerslongsの両方をパラメーターとして使用できます。

2.1. addExact()

2つのパラメーター、加算のthrowing an ArithmeticException in case of overflow (which goes for all *Exact() methods)を加算します。

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

2.2. substractExact()

最初のパラメーターから2番目のパラメーターの値を減算し、減算がオーバーフローした場合はArithmeticExceptionをスローします。

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

2.3. incrementExact()

パラメータを1つインクリメントし、オーバーフローの場合はArithmeticExceptionをスローします。

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

2.4. decrementExact()

パラメータを1つデクリメントし、オーバーフローの場合はArithmeticExceptionをスローします。

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

2.5. multiplyExact()

2つのパラメーターを乗算し、積がオーバーフローした場合に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

2番目の例では、明確ではないため、説明が必要です。The overflow is due to the Integer.MIN_VALUE being −2.147.483.648, and on the other side the Integer.MAX_VALUE being 2.147.483.647であるため、戻り値は1単位でIntegerに収まりません。

3. その他の方法

3.1. floorDiv()

最初のパラメーターを2番目のパラメーターで除算してから、結果に対して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() for two positive numbers is the same as % operatorです。 別の例を見てみましょう。

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

floorDiv(-5, 3)は-1ではなく-2であるため、2ではなく1を返します。

3.3. nextDown()

パラメータのすぐ下の値を返します(floatまたはdoubleパラメータをサポートします):

float f = Math.nextDown(3);  // returns 2.9999998
double d = Math.nextDown(3); // returns 2.999999761581421

4. 結論

この記事では、Javaプラットフォームのバージョン8でクラスjava.lang.Mathに追加されたすべての新しいメソッドの機能について簡単に説明し、それらの使用方法の例もいくつか見てきました。

いつものように、完全なソースコードはover on GitHubで利用できます。