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


Java Double.equals()用法及代碼示例


java.lang.Double.equals()是java中的內置函數,用於將該對象與指定對象進行比較。當且僅當參數不為null且是包含與此對象相同的double值的Double對象時,結果才為true。如果兩個對象都不相同,則返回false。在所有其他情況下,compareTo方法應該是首選。

用法:

public boolean equals(Object obj)

參數:該方法僅接受一個參數。
obj –傳遞的對象是要與之進行比較的對象。


返回值:與參數中傳遞的對象進行比較後,該函數返回一個布爾值。當且僅當參數不為null且是包含與此對象相同的double值的Double對象時,才返回true。如果對象不同,則返回false。

以下示例程序旨在說明java.lang.Double.equals()方法的使用:

示例1:

// Java program to demonstrate 
// of java.lang.Double.equals() method 
import java.lang.*; 
  
class Gfg1 { 
  
    public static void main(String args[]) 
    { 
  
        // When two objects are different 
        Double obj1 = new Double(123123); 
        Double obj2 = new Double(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 Double(12345); 
        obj2 = new Double(12345); 
        System.out.print("Object1 & Object2: "); 
        if (obj1.equals(obj2)) 
            System.out.print("Equal"); 
        else
            System.out.print("Not Equal"); 
    } 
}
輸出:
Object1 & Object2: Not equal
Object1 & Object2: Equal

示例2:沒有傳遞任何參數時。

// Java program to demonstrate 
// of java.lang.Double.equals() method 
import java.lang.Math; 
  
class Gfg1 { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
  
        // When no argument is passed 
        Double obj1 = new Double(124); 
        Double obj2 = new Double(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 Double.equals(Object) is not applicable
      (actual and formal argument lists differ in length)
1 error

示例3:除了對象以外的任何東西都作為參數傳遞時。

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


相關用法


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