• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Natural Ordering in HashSet for objects

 
Matloob Hussain
Ranch Hand
Posts: 37
Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

 
Ikpefua Jacob-Obinyan
Ranch Hand
Posts: 394
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Matloob Hussain
Ranch Hand
Posts: 37
Java MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ikpefua once again....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic