Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection that will maintain insertion order and no duplicates [duplicate]

In Java collection which collection will doesn't allow duplicates and which also preserve insertion order of data?

like image 984
Vishwanath.M Avatar asked May 10 '13 10:05

Vishwanath.M


People also ask

What collection does not allow duplicates?

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

Which collection maintains the insertion order?

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 Following maintain insertion order and accept duplicates entries?

Which of the following Sets maintains the insertion order? LinkedHashSet maintains the order in which the elements are inserted.

Does HashSet maintain insertion order?

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.


1 Answers

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)

like image 174
sanbhat Avatar answered Oct 29 '22 20:10

sanbhat