📜  compare()方法如何在Java

📅  最后修改于: 2021-05-20 07:26:37             🧑  作者: Mango

先决条件:比较接口在Java中,TreeSet中使用Java

Java的compare()方法比较作为参数给出的两个特定于类的对象(x,y)。它返回值:

  • 0:如果(x == y)
  • -1:如果(x
  • 1:如果(x> y)

句法:

public int compare(Object obj1, Object obj2)

其中obj1和obj2是使用compare()方法进行比较的两个对象。

例子:

展示使用Integer类的compare()方法的工作方式。

// Java program to demonstrate working
// of compare() method using Integer Class
  
import java.lang.Integer;
  
class Gfg {
  
    // driver code
    public static void main(String args[])
    {
        int a = 10;
        int b = 20;
  
        // as 10 less than 20,
        // Output will be a value less than zero
        System.out.println(Integer.compare(a, b));
  
        int x = 30;
        int y = 30;
  
        // as 30 equals 30,
        // Output will be zero
        System.out.println(Integer.compare(x, y));
  
        int w = 15;
        int z = 8;
  
        // as 15 is greater than 8,
        // Output will be a value greater than zero
        System.out.println(Integer.compare(w, z));
    }
}
输出:
-1
0
1

如何评估返回值:

compare()方法的内部工作可以在以下伪代码的帮助下可视化:

// Converting the two objects to integer
// for comparison
int intObj1 = (int)obj1;
int intObj2 = (int)obj2;
  
// Get the difference
int difference = intObj1 - intObj2;
  
if (difference == 0) {
  
    // Both are equal
    return 0;
}
else if (difference < 0) {
  
    // obj1 < obj2
    return -1;
}
else {
  
    // obj1 > obj2
    return 1;
}

用这种方法可视化compare()方法:

// Java program to demonstrate working
// of compare() method
  
import java.lang.Integer;
  
class Gfg {
  
    // Function to compare both objects
    public static int compare(Object obj1, Object obj2)
    {
  
        // Converting the two objects to integer
        // for comparison
        int intObj1 = (int)obj1;
        int intObj2 = (int)obj2;
  
        // Get the difference
        int difference = intObj1 - intObj2;
  
        if (difference == 0) {
  
            // Both are equal
            return 0;
        }
        else if (difference < 0) {
  
            // obj1 < obj2
            return -1;
        }
        else {
  
            // obj1 > obj2
            return 1;
        }
    }
  
    // driver code
    public static void main(String args[])
    {
        int a = 10;
        int b = 20;
  
        // as 10 less than 20,
        // Output will be a value less than zero
        System.out.println(compare(a, b));
  
        int x = 30;
        int y = 30;
  
        // as 30 equals 30,
        // Output will be zero
        System.out.println(compare(x, y));
  
        int w = 15;
        int z = 8;
  
        // as 15 is greater than 8,
        // Output will be a value greater than zero
        System.out.println(compare(w, z));
    }
}
输出:
-1
0
1

compare()方法的各种可能实现