Guava – Longs.checkedSubtract()方法与实例

Guava – Longs.checkedSubtract方法及实例

checkedSubtract(long a, long b)是Guava的LongMath类的一个方法,它接受两个参数a和b,并返回它们的差。

语法:

public static long checkedSubtract(long a, long b)

参数: 该方法接受两个长值a和b并计算它们的差值。

返回值:该方法返回传递给它的长值的差值,只要它不溢出。

异常情况: CheckedSubtract(long a, long b)方法,如果差值即(a – b)在有符号长运算中溢出,则抛出ArithmeticException。

下面的例子说明了上述方法的实现。

例1:

// Java code to show implementation of
// checkedSubtract(long a, long b) method
// of Guava's LongMath class
  
import java.math.RoundingMode;
import com.google.common.math.LongMath;
  
class GFG {
  
    // Driver code
    public static void main(String args[])
    {
        long a1 = 25;
        long b1 = 36;
  
        // Using checkedSubtract(long a, long b)
        // method of Guava's LongMath class
        long ans1 = LongMath.checkedSubtract(a1, b1);
  
        System.out.println("Difference of " + a1 + " and "
                           + b1 + " is: " + ans1);
  
        long a2 = 150;
        long b2 = 667;
  
        // Using checkedSubtract(long a, long b)
        // method of Guava's LongMath class
        long ans2 = LongMath.checkedSubtract(a2, b2);
  
        System.out.println("Difference of " + a2 + " and "
                           + b2 + " is: " + ans2);
    }
}

输出:

Difference of 25 and 36 is: -11
Difference of 150 and 667 is: -517

例2:

// Java code to show implementation of
// checkedSubtract(long a, long b) method
// of Guava's LongMath class
  
import java.math.RoundingMode;
import com.google.common.math.LongMath;
  
class GFG {
  
    static long findDiff(long a, long b)
    {
        try {
  
            // Using checkedSubtract(long a, long b) method
            // of Guava's LongMath class
            // This should throw "ArithmeticException"
            // as the difference overflows in signed
            // long arithmetic
            long ans = LongMath.checkedSubtract(a, b);
  
            // Return the answer
            return ans;
        }
        catch (Exception e) {
            System.out.println(e);
            return -1;
        }
    }
  
    // Driver code
    public static void main(String args[])
    {
        long a = Long.MIN_VALUE;
        long b = 452;
  
        try {
  
            // Function calling
            findDiff(a, b);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

java.lang.ArithmeticException: overflow

参考资料:

https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/LongMath.html#checkedSubtract-long-long-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程