📜  Java番石榴 |带有示例的短类的 compare() 方法

📅  最后修改于: 2022-05-13 01:54:22.189000             🧑  作者: Mango

Java番石榴 |带有示例的短类的 compare() 方法

Guava 的 Shorts 类的Shorts.compare()方法用于比较两个指定的short值。这些值作为参数传递,比较结果作为第一个值和第二个值的差值。因此,它可以是正数、零或负数。

句法:

public static int compare(short x, short y)

参数:此方法接受两个参数:

  • x:这是要比较的第一个 Short 对象。
  • y:要比较的 Short 对象。

返回类型:它返回一个int值。它返回:

  • 0 如果“x”等于“y”,
  • 正值“x”大于“y”,
  • 负值“x”小于“y”

下面是Java中 compare() 方法的实现:
示例 1:

// Java code to show implementation of
// Guava's Shorts.compare() method
import com.google.common.primitives.Shorts;
  
class GFG {
    public static void main(String[] args)
    {
  
        short a = 4;
  
        short b = 4;
  
        // compare method in Short class
        int output = Shorts.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 4 and 4 : 0

示例 2:

// Java code to show implementation of
// Guava's Shorts.compare() method
import com.google.common.primitives.Shorts;
  
class GFG {
    public static void main(String[] args)
    {
  
        short a = 4;
  
        short b = 2;
  
        // compare method in Short class
        int output = Shorts.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 4 and 2 : 2

示例 3:

// Java code to show implementation of
// Guava's Shorts.compare() method
import com.google.common.primitives.Shorts;
  
class GFG {
    public static void main(String[] args)
    {
  
        short a = 2;
  
        short b = 4;
  
        // compare method in Short class
        int output = Shorts.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 2 and 4 : -2