Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashSet or ArrayList

I wish to

  1. Avoid duplicated item being inserted.
  2. When I iterate through the collection class, the returned item is same as insertion order.

May I know, what thing I should consider, to choose either ArrayList (explicitly perform contains check before insertion) or LinkedHashSet?

Thanks.

like image 405
Cheok Yan Cheng Avatar asked Aug 21 '10 15:08

Cheok Yan Cheng


People also ask

Is ArrayList or LinkedList better?

ArrayList is faster in storing and accessing data. LinkedList is faster in manipulation of data.

Is LinkedHashSet slower than HashSet?

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.

What is the difference between LinkedHashSet and LinkedList?

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.

Which is faster ArrayList or HashSet?

As a conclusion, we can learn, that the contains() method works faster in HashSet compared to an ArrayList.


3 Answers

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))

like image 82
Klark Avatar answered Sep 22 '22 22:09

Klark


Use LinkedHashSet if you don't want duplicate items inserted.

like image 44
True Soft Avatar answered Sep 24 '22 22:09

True Soft


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.

like image 25
JRL Avatar answered Sep 23 '22 22:09

JRL