File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hashcodes in hashset 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 "Hashcodes in hashset" Watch "Hashcodes in hashset" New topic

Hashcodes in hashset

amarkirt saroay
Ranch Hand

Joined: Mar 16, 2008
Posts: 167
import java.util.*;
public class WS{
private String s;
public WS(String s){this.s=s;}
public static void main(String []p)
HashSet<object> hs=new HashSet<Object>();
WS ws1=new WS("kt");
WS ws2=new WS("kt");
String s1=new String("kt");
String s2=new String("kt");


Why is output =3?

Nikhil Raj

Joined: Mar 20, 2008
Posts: 16
Remember that a HashSet(any Set in general) will store only distinct objects.Here you add two Sring references(s1 & s2) to the HashSet.But the two String references refer to the same String object with value "kt".Hence the second duplicate object wont be added to the hashmap and so the final size would be 3.
Jelle Klap

Joined: Mar 10, 2008
Posts: 1951

Minor nitpick:

References s1 and s2 in fact point to two distinct objects, which happen to represent the same value "kt". For String objects the result of the equals() method is based on that value, instead of the object id (referential equality).

HashSet's add() method uses the result of the equals() method to prevent multiple references that point to equal objects from being added. Therefore a copy of reference s2 will not be added, because the HashSet already contains a reference to an equal object; the copy of reference s1 which was added previously.

All this does not apply to the objects reffered to by ws1 and ws2 respectively, because the class WS does not override the equals() method inherited from java.lang.Object (which IS based on object id). So when the equals() method is used to compare the two distinct WS instances for equality, the comparison does not hold eventhough both instances are meant to represent the same value "kt". As a result the HashSet will contain references to both WS instances.

Two references to two distinct WS instances, and one reference to a String instance, makes a total of 3, which is the value returned HashSet's size() method.
[ March 22, 2008: Message edited by: Jelle Klap ]

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
I agree. Here's the link:
subject: Hashcodes in hashset
It's not a secret anymore!