當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Long equals()用法及代碼示例


java.lang.Long.equals()是java中的內置函數,用於將該對象與指定對象進行比較。當且僅當參數不為null,並且是一個Long對象,並且該對象包含與該對象相同的long值時,結果才為true。如果兩個對象都不相同,則返回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


相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 Java Long equals() method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。