Doubt in HashSet

I have a class which has a String variable. I am adding objects of this class in a HashSet. However, duplicate values are getting added in the HashSet even though I have overriden the equals method.

Any idea why this is happening?

My code is as below.

Thanks for help in advance.

MG

-

import java.util.*;

public class HashSetTest {

public static void main(String[] args) {

HashSet<MyStrings> hs = new HashSet<MyStrings>();

System.out.println(hs.add(new MyStrings("SCJP")));

System.out.println(hs.add(new MyStrings("SCJD")));

System.out.println(hs.add(new MyStrings("MCSE")));

System.out.println(hs.add(new MyStrings("CSQA")));

System.out.println(hs.add(new MyStrings("SCJP")));

}

}

class MyStrings {

String str;

MyStrings(String s) {

str = s;

}

public String getValue() {

return str;

}

public boolean equals(Object obj) {

System.out.println("In equals");

if((obj instanceof MyStrings) && ((MyStrings) obj).getValue() == this.str) return true;

else return false;

}

}

-

[1182 byte] By [mona_ga] at [2007-11-26 13:29:37]
# 1
Got the answer from old topic in forum.Need to provide the hashCode() method in MyStrings class.Even with a simple hashCode() method as below the code runs fine.public int hashCode() {return 21;}
mona_ga at 2007-7-7 20:34:15 > top of Java-index,Core,Core APIs...
# 2

> Got the answer from old topic in forum.

>

> Need to provide the hashCode() method in MyStrings

> class.

> Even with a simple hashCode() method as below the

> code runs fine.

>

> public int hashCode() {

> return 21;

> }

That will work correctly, but if you have many items in the set, it will be slow to find one. You're aking the hash useless and turning it in into a linear search.

http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf

jverda at 2007-7-7 20:34:15 > top of Java-index,Core,Core APIs...
# 3

Hi Mona,

Whenever you override "equals()" , make it a must to override "hashcode()" also. Collection (Hashtable, HashMap, HashSet) etc stores and retrieves objects based on hashing - using hashcode values. Even if the hashCode is a constant value, it concurs to the hashCode contract. But there are ways to generate hashCode better than always returning a constant value. If two objects are equal based on "equals()" method, then hashCodes of both the objects must be equal. If two objects are not equal based on equals() method, hashCodes may not be equal. So it is always a good practice to generate hashCode based on appropriate logics.

Regards,

Shambhu

Shambhu_79a at 2007-7-7 20:34:15 > top of Java-index,Core,Core APIs...
# 4
In this case it would be better and equally easy to just return the String field's hashCode. FYI, Jakarta Commons Lang has a HashCodeBuilder class[url] http://jakarta.apache.org/commons/lang/api-release/org/apache/commons/lang/builder/package-summary.html[/url]
Lokoa at 2007-7-7 20:34:15 > top of Java-index,Core,Core APIs...