When to use the Collection Classes(HashSet, LinkedHashSet,
TreeSet....etc) in real time scenario ?



When to use the Collection Classes(HashSet, LinkedHashSet, TreeSet....etc) in real time scenario ?..

Answer / manja

LinkedHashSet, TreeSet and HashSet are three of most popular implementation of Set interface in Java Collection Framework. Since they implement Set interface, they follow it's contract for not allowing duplicates. All these implementation except, TreeSet uses equals() method to check for duplicates, on the other hand TreeSet use compareTo() or compare() method for comparing objects and can break Set interface contract of unique element, if equals method is not consistent with compareTo() or compare() method. In this Java Collection tutorial, we will see difference between LinkedHashSet vs TreeSet vs HashSet on different points e.g. speed, performance, ordering, synchronization etc. Based upon these differences we can also decide when to use LinkedHashSet vs TreeSet vs HashSet in Java. TL;DR, Use HashSet for all general purpose usage i.e. where you need to store only unique elements without any ordering requirement. If you need to maintain order on which elements are added into Set then use LinkedHashSet, it provides ordering with little impact on performance. Use TreeSet when you absolutely nee to keep elements in specific sorted order e.g. keeping employee in increasing order of their age or salary. Remember, TreeSet is significantly slower than LinkedHashSet and HashSet because of this sorting overhead.

Is This Answer Correct ?    6 Yes 0 No

Post New Answer

More Java J2EE AllOther Interview Questions

what is difference between web server and application server?

1 Answers   L&T,


Difference b/w >> and >>> ?

1 Answers   Adobe, Infosys,


can u draw class/object diagram for ATM

0 Answers   HCL, Zycus Infotech,


whats the relation ship between LDAP and JNDI?

1 Answers  


How many controlers are there in spring? Plz send me ans

1 Answers   HCL,






What causes Out of Memory exception?

5 Answers   CTS,


Which is the better framework for web applications, struts or spring, and why?

1 Answers   IBM, TATA,


"Sun Certified Java Programmer" This is one String , we need to print SCJP, write the java code dynamically? pls reply this questions

6 Answers   Photon,


Hi Friends , am newbie to ajax. For example just consider one account registration - A form contains 8 text fields with submit button. In this form second texbox contains "username " . On right side of text box there is a label box . On clilck action i need to determine user is available or not. Is it possible on clicking label or should i click submit button.

0 Answers  


whatis arguments &what is default argument

2 Answers   CTS,


What are the types of interface used in the java collections? : java collections

0 Answers  


What is need of DAO? Write one simple DAO example?

2 Answers   IBM,


Categories