📜  Java Long equals() 方法和示例

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

Java Long equals() 方法和示例

Java .lang.Long.equals()是Java中的一个内置函数,用于将此对象与指定对象进行比较。当且仅当参数不为 null 并且是包含与该对象相同的 long 值的 Long 对象时,结果才为真。如果两个对象不相同,则返回 false。在所有其他情况下,应该首选 compareTo 方法。

句法:

public boolean equals(Object obj)  

Parameter: 
obj - The passed object is the object that is to be compared with. 

回报:
该函数在与参数中传递的对象进行比较后返回一个布尔值。当且仅当参数不为 null 并且是包含与该对象相同的 long 值的 Long 对象时,它才返回 true。如果对象不相同,则返回 false。

程序1:下面的程序演示了函数的工作。

// Java program to demonstrate
// of java.lang.Long.equals() method
import java.lang.Math;
  
class Gfg1 {
  
    public static void main(String args[])
    {
  
        // when two objects are different
        Long obj1 = new Long(123123);
        Long obj2 = new Long(164165);
        System.out.print("Object1 & Object2: ");
        if (obj1.equals(obj2))
            System.out.println("Equal");
        else
            System.out.println("Not equal");
  
        // when two objects are equal
        obj1 = new Long(12345);
        obj2 = new Long(12345);
        System.out.print("Object1 & Object2: ");
        if (obj1.equals(obj2))
            System.out.print("Equal");
        else
            System.out.print("Not Equal");
    }
}

输出:

object1 and object2 are not equal
object1 and object2 are equal

程序2:下面的程序演示了不传递参数时函数的工作

// Java program to demonstrate
// of java.lang.Long.equals() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
  
        // when no argument is passed
        Long obj1 = new Long(124);
        Long obj2 = new Long(167);
        System.out.print("Object1 & Object2: ");
        if (obj1.equals())
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
    }
}

输出:

prog.java:15: error: no suitable method found for equals(no arguments)
      if(obj1.equals())
             ^
    method Object.equals(Object) is not applicable
      (actual and formal argument lists differ in length)
    method Long.equals(Object) is not applicable
      (actual and formal argument lists differ in length)
1 error

程序 3:下面的程序演示了在参数中传递除对象以外的任何内容时函数的工作

// Java program to demonstrate
// of java.lang.Long.equals() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
  
        // when anything other than argument is passed
  
        Long obj1 = new Long(124);
  
        System.out.print("Object1 & Object2: ");
        if (obj1.equals("gfg"))
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
    }
}

输出:

Object1 & Object2:  Not Equal