2013-07-31 315 views
0

我讀到.equals()比較對象的值,而==比較引用(即 - 變量指向的內存位置)。在這裏看到:What is the difference between == vs equals() in Java?
.equals()和==之間的區別是什麼?

但要遵循下面的代碼段:

package main; 

public class Playground { 

    public static void main(String[] args) { 
     Vertex v1 = new Vertex(1); 
     Vertex v2 = new Vertex(1); 

     if(v1==v2){ 
      System.out.println("1"); 
     } 
     if(v1.equals(v2)){ 
      System.out.println("2"); 
     } 
    } 
} 

class Vertex{ 
    public int id; 

    public Vertex(int id){ 
     this.id = id; 
    } 
} 

輸出:
(沒有)

它不應該被打印2?

+2

你或許應該選擇那些不會停課的另外一個問題重複一個標題。 –

+0

我有一個問題:hashmap如何查找對象?可以說我有一個頂點id = 5。我可以創建一個id = 5的新頂點並將其傳遞給hashmap的get方法嗎? – user2316667

+0

@ user2316667如果你先**閱讀**然後**測試**,那就太好了。然後你會得到你的答案。 –

回答

6

您需要爲Vertex類實現您自己的.equals()方法。

默認情況下,您正在使用Object.equals方法。 From the docs, this is what it does:

Object類的equals方法實現了最有區別的 對象上的可能等價關係;也就是說,對於任何非空 引用值x和y,當且僅當x 和y引用同一對象(x == y的值爲true)時,此方法返回true。

你可以做這樣的事情:

@Override 
public boolean equals(Object obj) { 
    if (obj == null) return false; 
    if (obj.getClass() != getClass()) return false; 
    Vertex other = (Vertex)obj; 
    return (this.id == other.id); 
} 
+0

和'hashCode'可能。 – Mena

+0

哦,我明白了,我非常感謝! – user2316667

+2

我更喜歡用if(obj.getClass()!= getClass() )'比使用'if(!(obj instanceof Vertex))'',因爲後者將允許子類等於它的父親 –

3

你需要重寫的equals()默認實現。默認的實現是Object#equals()

public boolean equals(Object obj) { 
    return (this == obj); 
} 

重寫版本是這樣的:

@Override 
public boolean equals(Object obj) 
{ 
    if(obj == this) return true; 
    if(obj == null) return false; 
    if(obj.getClass() != getClass()) return false; 
    return ((Vertex) obj).id == this.id; 
} 
+0

OP想'返回this.id == id;' –

+0

@GrijeshChauhan OP說'不應該打印2?'。 –

+0

'obj.id = this.id'與'obj.id == this.id'不一樣 –

相關問題