aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes LinkedHashSet 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 "LinkedHashSet" Watch "LinkedHashSet" New topic
Author

LinkedHashSet

swapna mallipudi
Greenhorn

Joined: Sep 10, 2009
Posts: 11
The Question is from CertPal. What is the output of the program?


Size is 5. I don't know what I am missing here. I was thinking LinkedHashSet doesn't allow duplicates. Then howcome the size is 5.

Thank you.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

I was thinking LinkedHashSet doesn't allow duplicates.

How do you know if a Lion is equal to another ?


[My Blog]
All roads lead to JavaRanch
Harpreet Singh janda
Ranch Hand

Joined: Jan 14, 2010
Posts: 317

In case of set it always first check the HashCode and the use the equals to compare the objects.
Lion class does not override the hashcode and equals method so two objects of lion class will never be equal until they are not pointing to same object. So there will not be any duplicate lion object but same is not true for String objects.

If you try the below code :


Output will be


See, there are 3 lion objects and 2 String objects Because String override equals method but Lion does not. If you override the equals and hashcode methods in Lion class you will get desired results.
Harpreet Singh janda
Ranch Hand

Joined: Jan 14, 2010
Posts: 317

Here is the modified version of above code:



and the output is



So the crux is : Whenever you are using an object with collections, always take care of hashcode and equals methods
Shailesh Phatak
Ranch Hand

Joined: Aug 27, 2009
Posts: 64
Harpreet Singh janda wrote:So the crux is : Whenever you are using an object with collections, always take care of hashcode and equals methods

It was a great help Harpreet


See Dreams With Open Eyes And Make It Real
jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
I am wondering how overriding equals() and hashcode() makes such a huge difference ?? Whats so special about equals and hashcode, that we should override them in user defined classes ??

Also which are those classes that override equals and hashcode , besides String and Wrapper Classes ?
Rajeev Trikha
Ranch Hand

Joined: Jan 29, 2010
Posts: 85
For two objects of a given class to be equal, they must have the same hashcode and meaningful equivalence defined within equal method. The default implementation in Object only gives two objects to be equal if they are of the same type and share the common reference.

For the exam purposes, it is useful to know that StringBuffer doesn't define equal method.


Rajeev Trikha (SCJP 6)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: LinkedHashSet