In Java collection which collection will doesn't allow duplicates and which also preserve insertion order of data?
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
ArrayList maintains the insertion order i.e order of the object in which they are inserted. HashSet is an unordered collection and doesn't maintain any order. ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.
Which of the following Sets maintains the insertion order? LinkedHashSet maintains the order in which the elements are inserted.
HashSet does not provide any method to maintain the insertion order. Comparatively, LinkedHashSet maintains the insertion order of the elements. We can not predict the insertion order in HashSet, but we can predict it in LinkedHashSet. The LinkedHashSet extends the HashSet, so it uses a hashtable to store the elements.
LinkedHashSet
As per the documentation
This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (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