Search code examples
javaduplicatesadditionhashset

What happens when I add duplicate element into HashSet? Is old element overwritten or not?


Say I want to add duplicate element in HashSet. We know that is not allowed. So I came across 2, let's say theories.

Under 'PROPERTIES, number 2' of this link, it says:

HashSet does not allow duplicate elements. If you try to insert a duplicate element, older element will be overwritten

But when I check docs that are provided to me in IDE, in method add(), it states:

* If this set already contains the element, the call leaves the set
* unchanged and returns {@code false}.

So does it overwrite(replace) old element or it leaves the set unchanged and returns false? :) Am I crazy of they say exactly the opposite?


Solution

  • The IDE is displaying an excerpt from the official specification (the javadocs) for the Set.add method.

    The IDE is correct. Trust the official documentation, not some "pretty" website.


    But how could people that made that site make such a big mistake then?

    Always remember that the primary motivation for websites like the one you found is to earn money from your page views. They often pay more attention to "search engine optimization" than they do the quality of their material.


    But the problem is those "random" sites sometimes make 'prettier' explanation of some concepts. Official docs are sometimes too hard to follow for me as a beginner.

    So which is preferable? Something that easy to read, but wrong? Or something that is accurate?

    In this case, you cannot argue that the official document is hard to understand. You yourself were able to see that the contradiction between the text taken from the official documentation and the 3rd-party website.

    My advice us to always try to read the Official javadocs first, and always believe it ahead of any other sources ... including StackOverflow answers!! The only thing that is more definitive1 is the OpenJDK source code.


    1 - And even that is debatable. On the one hand, the code determines what actually happens. On the other hand, the code may change from one version to another. So relying on behavior that is not specified in the javadocs may result in portability issues.