📜  Java中的简短 compareTo() 方法和示例

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

Java中的简短 compareTo() 方法和示例

Short 类的compareTo()方法是Java中的一个内置方法,用于对两个 Short 对象进行数值比较。

句法:

public int compareTo(Short otherShort)

参数:此方法接受一个强制参数otherShort ,它是要比较的 Short 对象。

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

  • 0 如果“otherShort”等于“thisShort”,
  • 正值“thisShort”小于“otherShort”,
  • 负值“otherShort”大于“thisShort”

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

// Java code to demonstrate
// Short compareTo() method
  
class GFG {
    public static void main(String[] args)
    {
  
        // creating a Short object
        Short a = new Short("4");
  
        // creating a Short object
        Short b = new Short("4");
  
        // compareTo method in Short class
        int output = a.compareTo(b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 4 and 4 : 0

示例 2:

// Java code to demonstrate
// Short compareTo() method
  
class GFG {
    public static void main(String[] args)
    {
  
        // creating a Short object
        Short a = new Short("4");
  
        // creating a Short object
        Short b = new Short("2");
  
        // compareTo method in Short class
        int output = a.compareTo(b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 4 and 2 : 2

示例 3:

// Java code to demonstrate
// Short compareTo() method
  
class GFG {
    public static void main(String[] args)
    {
  
        // creating a Short object
        Short a = new Short("2");
  
        // creating a Short object
        Short b = new Short("4");
  
        // compareTo method in Short class
        int output = a.compareTo(b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 2 and 4 : -2