开发者

Why Hashset doesn't take duplicate values?

I have a doubt regarding hashset. Why doesn't Hashset take duplicate elements? I know it implements Set interface and places the values in a hashtable. What I mean is what may be the code internally written f开发者_如何学运维or not taking duplicate values?


Precisely for the reason you mentioned, a HashSet implements the Set interface:

Set

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

You want duplicates? Use List.


Here is some information about it

Collision Resolution

And here is the source


Because, by definition, a set is a thing that does not contain duplicates.


HashSet does not allows duplicate values, why because HashSet Class contain add() method, it will check before while adding elements inside HashSet. if we are trying adding duplicate values it returns false, so not allowed.

here present, e both are equal returns false.Object PRESENT; public boolean add(E e) { return map.put(e, PRESENT)==null; }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜