Java Tutorial: TreeSet,HashSet


Linked list in java can be used as per our need such as HashSet

but if you want linkedlist with sorted data then??

don’t worry java hs inbuild TreeSet class which sorts data stored in it in alphabetical order.

see following code you will get to know how does TreeSet ,HashSet works.


It gives following output to me

content of name [bhushan, bhalchandra, sonawane]
content of name after setting  [ BhUsHaN, bhalchandra, sonawane]
content of frnds [rohit, rohini, aanchal, ojas, chinmoy]
rohit entered HashSet
rohini entered HashSet
aanchal entered HashSet
ojas entered HashSet
chinmoy entered HashSet
rohit entered TreeSet
rohini entered TreeSet
aanchal entered TreeSet
ojas entered TreeSet
chinmoy entered TreeSet
content of HashSet frnds [aanchal, chinmoy, ojas, rohit, rohini]
content of TreeSet frnds [aanchal, chinmoy, ojas, rohini, rohit]
content of frnds before [rohit, rohini, aanchal, ojas, chinmoy]

HashSet does not guarantee the order of its elements, because
the process of hashing doesn’t usually lend itself to the creation of sorted sets. If you
need sorted storage, then another collection, such as TreeSet, is a better choice.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s