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


Java Object equals(Object obj)用法及代碼示例


equals(Object obj) 是 Object 類的方法。此方法用於比較給定的對象。建議重寫 equals(Object obj) 方法以獲得我們自己的對象相等條件。

用法

public boolean equals(Object obj)

參數

obj- 它是參考對象。

返回

如果此對象與 obj 參數相同,則返回 true,否則返回 false。

例子1

public class JavaObjectequalsExample1 {
   static int a = 10, b=20;  
    int c; 
    // Constructor 
    JavaObjectequalsExample1() 
    { 
        System.out.println("Addition of 10 and 20:");
        c=a+b;
        System.out.println("Answer:"+c);        
    } 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        System.out.println("1st object created...");
        JavaObjectequalsExample1 obj1 = new JavaObjectequalsExample1();  
        System.out.println("2nd object created...");
        JavaObjectequalsExample1 obj2 = new JavaObjectequalsExample1();  
        System.out.println("Objects are equal:" + obj1.equals(obj2)); 
    }  
}

輸出:

1st object created...
Addition of 10 and 20:
Answer:30
2nd object created...
Addition of 10 and 20:
Answer:30
Objects are equal:false

例子2

public class JavaObjectequalsExample2{
   static int a = 10, b=20;  
    int c; 
    // Constructor 
    JavaObjectequalsExample2() 
    { 
        System.out.println("Addition of 10 and 20:");
        c=a+b;
        System.out.println("Answer:"+c);        
    } 
    JavaObjectequalsExample2(int x, int y) 
    { 
        System.out.println("Parameterized Constructors");
        System.out.println("Addition " +x+ " and " +y);
        c=x+y;
        System.out.println("Answer:"+c);        
    } 
    // Driver code 
    public static void main(String args[]) 
    { 
        System.out.println("1st object created...");
        JavaObjectequalsExample2 obj1 = new JavaObjectequalsExample2();  
        System.out.println("2nd object created...");
        JavaObjectequalsExample2 obj2 = new JavaObjectequalsExample2(2,3);  
        System.out.println("Objects are equal:" + obj1.equals(obj2)); 
    }  
}

輸出:

1st object created...
Addition of 10 and 20:
Answer:30
2nd object created...
Parameterized Constructors
Addition 2 and 3
Answer:5
Objects are equal:false





相關用法


注:本文由純淨天空篩選整理自 Java Object equals(Object obj) Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。