File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hashcodes in hashset

 
amarkirt saroay
Ranch Hand
Posts: 167
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Nikhil Raj
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1951
7
Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic