📜  Java中的布尔 compareTo() 方法及示例

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

Java中的布尔 compareTo() 方法及示例

Boolean 类的compareTo()方法是Java中的一个内置方法,用于将给定的 Boolean 实例与当前实例进行比较。

句法:

BooleanObject.compareTo(Boolean a)

参数:它需要一个布尔值a作为参数,该参数将与当前实例进行比较。

返回类型:函数的返回类型是int 。它返回:

  • 0 如果“a”等于“b”,
  • 如果“a”为假且“b”为真,则为负值,
  • 如果“a”为真且“b”为假,则为正值。

下面是说明布尔类的 compareTo() 方法的程序:

方案一:

// Java code to implement
// compareTo() method of Boolean class
  
class GeeksforGeeks {
  
    // Driver method
    public static void main(String[] args)
    {
  
        // Boolean object
        Boolean a = new Boolean(true);
  
        // Boolean object
        Boolean b = new Boolean(true);
  
        // compare method
        System.out.println(a + " comparing with " + b
                           + " = " + a.compareTo(b));
    }
}
输出:
true comparing with true = 0

方案二:

// Java code to implement
// compareTo() method of Java class
  
class GeeksforGeeks {
  
    // Driver method
    public static void main(String[] args)
    {
  
        // Boolean object
        Boolean a = new Boolean(true);
  
        // Boolean object
        Boolean b = new Boolean(false);
  
        // compare method
        System.out.println(a + " comparing with " + b
                           + " = " + a.compareTo(b));
    }
}
输出:
true comparing with false = 1

方案 3:

// Java code to implement
// compareTo() method of Java class
  
class GeeksforGeeks {
  
    // Driver method
    public static void main(String[] args)
    {
  
        // Boolean object
        Boolean a = new Boolean(false);
  
        // Boolean object
        Boolean b = new Boolean(true);
  
        // compare method
        System.out.println(a + " comparing with " + b
                           + " = " + a.compareTo(b));
    }
}
输出:
false comparing with true = -1