Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals and hashcode

 
kenneth See
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Do you know why the following program cannot get the result -12 1? JVM seems think object n1 and n2 are different. I have alrady override the equals() and hashcode() methods but I still cannot make the JVM think the object n1 and n2 are the same.

Hope someone can help me.

import java.util.*;
class Nearly {
String value;
Nearly(String v) {
value = v;
}

public int hashcode() {
return 1;
}
public boolean equals(Object o) {
if ((o instanceof Nearly)) {
if (value.charAt(0) == ((Nearly) o).value.charAt(0)) return true;
}
return false;
}
public static void main(String[] sss){
Nearly n1 = new Nearly("aaa");
Nearly n2 = new Nearly("aaa");
String s ="-";
if (n1.equals(n2)) s += "1";
if (n1 == n2) s+= "2";
Set <Nearly> set = new HashSet<Nearly>();
set.add(n1);
set.add(n2);
System.out.println(s + " " + set.size());
}
}
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to override the hashCode() method -- notice the capital C.

Henry
 
kenneth See
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Henry,

Thanks a lot. It works. I just have one more question in my program:

n1 and n2 have the same hashcode and same value ("aaa"). Why n1==n1 is still not true? It is because I still cannot get it print out the result -12 1.

Thanks for your help.

Kenneth
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
n1 and n2 have the same hashcode and same value ("aaa"). Why n1==n1 is still not true?


Because they are not the same object. The equals() method is used to determine if two objects are equal in value. The "==" operator is used to determine if both references are referring to the same object.

In this example, it is two different objects, that have the same value. They are considered to be equal, but they are not the same object.

Now, if you had done this...



Then they would be the same object.

Henry
[ November 06, 2008: Message edited by: Henry Wong ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic