Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java collection insertion: Set vs. List

I'm thinking about filling a collection with a large amount of unique objects. How is the cost of an insert in a Set (say HashSet) compared to an List (say ArrayList)?

My feeling is that duplicate elimination in sets might cause a slight overhead.

like image 1000
Will Avatar asked May 18 '11 11:05

Will


People also ask

Which is better List or Set in Java?

The main difference between List and Set is that List allows duplicates while Set doesn't allow duplicates. List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.

What is the difference between a List and a Set in Java?

List is an ordered sequence of elements. User can easily access element present at specific index and can insert element easily at specified index. Set is an unordered list of elements. Set does not have duplicate elements.

Which is faster List or Set in Java?

As Will has noted, because of the dictionary structure HashSet is probably a bit slower than an ArrayList (unless you want to insert "between" existing elements). It also is a bit larger.


1 Answers

There is no "duplicate elimination" such as comparing to all existing elements. If you insert into hash set, it's really a dictionary of items by hash code. There's no duplicate checking unless there already are items with the same hash code. Given a reasonable (well-distributed) hash function, it's not that bad.

As Will has noted, because of the dictionary structure HashSet is probably a bit slower than an ArrayList (unless you want to insert "between" existing elements). It also is a bit larger. I'm not sure that's a significant difference though.

like image 56
Konrad Garus Avatar answered Sep 22 '22 06:09

Konrad Garus