File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Natural Ordering in HashSet for objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Natural Ordering in HashSet for objects" Watch "Natural Ordering in HashSet for objects" New topic
Author

Natural Ordering in HashSet for objects

Matloob Hussain
Ranch Hand

Joined: May 13, 2011
Posts: 37

What does mean the natural ordering in HashSet for objects?

As I know:
TreeSet use compareTo() method to check the duplicates and sorting order.

LinkedHashSet use equals() and hashCode() methods to check the duplicates and follow the insersion order.

HashSet use equals() and hashCode() methods to check the duplicates and follow the natural order.

natural ordering for number and string are simple but how does it works for objects in this code?



Matloob
OCPJP 1.6
OCPWCD in progress.....
Ikpefua Jacob-Obinyan
Ranch Hand

Joined: Aug 31, 2010
Posts: 394

Matloob wrote:
HashSet use equals() and hashCode() methods to check the duplicates and follow the natural order.


Hello Matloob, the above statement ia PARTIALLY correct, what I mean is that HashSet makes NO guarantees as to the iteration order of the set; in particular, it does NOT guarantee that the order will remain constant over time.
If you have any doubts, you can consult the API .

And for the purpose of the exams, if you find any questions that ask about the result of a HashSet order, you will find options like "output depends on Hashing" or "Output Not Definded" etc, thats the correct answer, do NOT try to check for ordering. (SAME Applies to numbers AND Strings).


OCPJP 6.
In Your Pursuit Towards Certification, NEVER Give Up.
Matloob Hussain
Ranch Hand

Joined: May 13, 2011
Posts: 37

Thanks Ikpefua once again....
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Natural Ordering in HashSet for objects
 
Similar Threads
Employee with same values is being added two times in HashSet
Using java.util.HashSet for Custom Class
Doubt in hashCode() and equals() method
Please explain the output