Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How sets avoid duplicates internally?

Tags:

java

I had a doubt about the set in Collections framework. How the set itself will identify duplicates and how it will come to know? Could anyone please explain how it is implemented? How hashcode and equals method will come into the picture? I need a brief explanation as it is really important for me.

like image 312
Kosuri Naresh Avatar asked Feb 25 '13 07:02

Kosuri Naresh


1 Answers

It roughly works like this

if (!collection.contains(element))
    collection.add(element);

And the contains method, would use equals/hashcode.

In TreeSet, the elements are stored in a Red-Black Tree, whereas HashSet, uses a HashMap.

Infact, the way it is added to the container is specific to the element (the spot on the tree, bucket in the hashtable), thus the adding itself uses equals/hashcode.

like image 191
Karthik T Avatar answered Sep 23 '22 00:09

Karthik T