aspose file tools*
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
Author

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");
hs.add(ws1);
hs.add(ws2);
hs.add(s1);
hs.add(s2);
System.out.println(hs.size());
}

}

Why is output =3?


SCJP-75%
SCWCD-82%
Nikhil Raj
Greenhorn

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
Bartender

Joined: Mar 10, 2008
Posts: 1666
    
    7

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.
 
jQuery in Action, 2nd edition
 
subject: Hashcodes in hashset
 
Similar Threads
Wrappers with String and Collections
HashSet Duplicate element ?
I am finding hashing a bit confusing please it in a bit detail