LinkedHashSet - This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet, without incurring the increased cost associated with TreeSet.
Same is said about LinkedHashMap vs TreeMap
What is this increased cost (LinkedHashMap vs TreeMap) exactly?
Does that mean that TreeSet needs more memory per element? LinkedHashSet needs more memory for two additional links, but TreeSet needs additional memory to store Map.Entry pair of elements (because implicitly based on TreeMap), besides LinkedHashSet is based on HashMap which also has Map.Entry pair of elements overhead...
So the difference is how fast a new element is added (in case of TreeSet it takes longer due to some "sorting").
What are other significant increased costs?
LinkedHashSet gives insertion, removing, and retrieving operations performance in order O(1). While TreeSet gives the performance of order O(log(n)) for insertion, removing, and retrieving operations. The performance of HashSet is better when compared to LinkedHashSet and TreeSet.
LinkedHashSet simply stores a collection of things. LinkedHashMap replaces the value with a duplicate key. LinkedHashSet not change the original value. LinkedHashMap has elements in key-value pairs so have only one null key and multiple null values.
TreeSet keeps the elements in order at all times. With ArrayList you just sort when you need to. With TreeSets the key must be embedded in the object you store in the collection.
HashSet is slightly faster than the LinkedHashSet. But both provide almost similar performance, Both provide o(1) complicity for inserting, removing, retrieving the object. Both the HashSet and LinkedHashSet allows only one null objects.
TreeSet
/TreeMap
have a higher time complexity for operations such ass add()
, contains()
(for TreeSet
), put()
, containsKey()
(for TreeMap
), etc... since they require logarithmic time to locate elements in the tree (or add elements to the tree), while LinkedHashSet
/LinkedHashMap
require expected constant time for those operations.
In terms of memory requirements, there's a very small difference:
TreeMap
entries hold key, value, 3 Entry
references (left, right, parent) and a boolean
.
LinkedHashMap
entries hold key, value, 3 Entry
references (next, before, after) and an int
.
When iterating a HashSet, the iteration order is generally the order of the hash of the object, which is generally not too useful if you want a predictable order.
If sane ordering is important you would generally need to use a TreeSet which iterates in sorted order but at a cost because maintaining the sorted order adds to the complexity of the process.
A LinkedHashSet can be used as a middle-ground solution to the seemingly insane ordering of a HashSet
by ensuring that the iteration order is at least consistent by using the insertion order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With