wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals and hashcode Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals and hashcode" Watch "equals and hashcode" New topic
Author

equals and hashcode

kenneth See
Greenhorn

Joined: Aug 21, 2008
Posts: 7
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
Sheriff

Joined: Sep 28, 2004
Posts: 18529
    
  40

You need to override the hashCode() method -- notice the capital C.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
kenneth See
Greenhorn

Joined: Aug 21, 2008
Posts: 7
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
Sheriff

Joined: Sep 28, 2004
Posts: 18529
    
  40

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 ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: equals and hashcode
 
Similar Threads
Why is this HashSet allowing duplicates?
equals & hashcode doubt
doubt in hashcode...
mechanism of equals(Object)?
hashCode() and equals()