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

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

What is deque in the java collections framework? : java collections

540


Explain the OOPS concept in Realtime Scenarion ? Take example as CAR. Please explain indetail ?

2565


What is the difference between comparable and comparator in java.util pkg?

592


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

589


What is iterator in the java collections framework? : java collections

537






What is an algorithm in java collection framework? : java collections

581


my interviewer asked me what technical specification you used how to answer that question

1935


What are the different types of features of the java collections framework? : java collections

575


HOW MUCH PERCENTAGE WE DEDUCT FOR OUR SUPPLIERS OR OTHER PROFESSIONALS

1580


What is java collection? : java collections

581


What are the differences between the java collection and the java list? : java collections

615


Which server-side script takes the input from JavaScript, can access the database if it needs to, and processes the data.

1600


What are the queues in the java collection framework? : java collections

552


What are the types of the main implementing classes in the map interfaces? : java collections

613


How is hashset maintained in memory by java ?

592