Rashmi
Rashmi

Reputation: 281

I have been asked this in interview . Is LinkedHashSet or LinkedList faster?

This was something asked to me in an interview. Among LinkedList and LinkedHashSet which is faster. What I understand is since hashCode and equals used along with LinkedHashSet then it will take time for LinkedHashSet to execute during a put operation. But what about the case where hashCode and equals are not used? Also is it right to compare the speed of LinkedList and LinkedHashSet. Because what I feel is the good design practice is to compare which interface we have to go List or Set and from there we have to decide which class we have to go for. Let me know your opinion on this.

Upvotes: 3

Views: 2095

Answers (1)

pnuts
pnuts

Reputation: 59442

From Jesper de Jong (in a context where ArrayList was also considered):

About creation, it's just as the other two, there's no reason to assume anything about how fast creating a new LinkedHashSet is. Since LinkedHashSet uses a doubly-linked list to maintain the order of its elements, accessing an element by index will be just as inefficient as with LinkedList. Checking if an element exists in the set will be more efficient.

Note that LinkedHashSet is a Set, which is a different thing than a List. A List can have duplicate elements, a Set cannot have duplicate elements. So you cannot just use LinkedHashSet as a replacement for ArrayList or LinkedList in any situation.

Upvotes: 1

Related Questions