My doubt is, why "a" is inserting in between "B" and "C".
A TreeSet orders the entries.
A LinkedHashSet preserves the insertion order.
A HashSet does not preserve the order of insertion, and is does not sort/order the entries. That means that when you iterate over the set, the entries are returned in an order that is hard to fathom ... and of no practical significance. There is no particular "reason" that "a"
is inserted at that point. That's just how it turned out ... given the set of input keys and the order in which they were inserted.
My only doubt is, how does Hashset works in Java.
It is implemented a hash table. Read the Wikipedia page on hash tables for a general overview, and the source code of java.util.HashMap
and java.util.HashSet
for the details.
The short answer is that HashSet
and HashMap
are both a hash table implemented as an array of hash chains.
And I know that, LinkedHashset follows doubly linkedlist. If it uses doubly linked list then how does it stores the elements?
LinkedHashSet
is essentially a hash table with an additional linked list that records the insertion order. The elements are stored in the main hash table ... and that is what provides fast lookup. Again, refer to the source code for details.
What does mean by doubly linkedlist and how does it works?
Read the article in Wikipedia on doubly linked lists.
Then where all these three Hashset, Treeset, Linkedhashset would be used in Java and which one has better performance in java?
There are a number of things to think about when choosing between these three classes (and others):
Do they provide the required functionality. For example, we've already seen that they have different behaviour with respect to the order of iteration.
Do they have the required concurrency properties? For example, are they thread-safe? do they deal with contention? do they allow concurrent modification?
How much space do they require?
What are the performance (time) characteristics.
On the last two points?
A
TreeSet
uses the least space, and aLinkedHashSet
uses the most.A
HashSet
tends to be fastest for lookup, insertion and deletion for larger sets, and aTreeSet
tends to be slowest.