I wish to
May I know, what thing I should consider, to choose either ArrayList (explicitly perform contains check before insertion) or LinkedHashSet?
Thanks.
ArrayList is faster in storing and accessing data. LinkedList is faster in manipulation of data.
HashSet gives better performance than the LinkedHashSet and TreeSet. The performance of LinkedHashSet is between HashSet and TreeSet. It's performance is almost similar to HashSet. But slightly in the slower side as it also maintains LinkedList internally to maintain the insertion order of elements.
LinkedList is the implementation of list and deque interface. LinkedHashSet on other hand is the implementation of set interface and it inherits Hashset class. LinkedList internally implements or we can say uses doubly linked list to store the elements.
As a conclusion, we can learn, that the contains() method works faster in HashSet compared to an ArrayList.
Definitely use LinkedHashSet. It is made for what you need. Searching entire ArrayList every time you need to insert something will be performance killer (O(n) every time))
Use LinkedHashSet
if you don't want duplicate items inserted.
A LinkedHashSet
seems to fit the bill perfectly.
When you build your own objects, and plan to use them in a Collection like LinkedHashSet
here. Don't forget to override both equals
and hashcode
for the item you are going to store in it.
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