59. Why HashSet can’t contain duplicated elements and can’t main the order of elements?

Why HashSet can’t contain duplicated elements ?

  • HashSet can’t contain duplicated elements because inside HashSet, it uses HashMap to store the elements
    —> The elements of HashSet are the key of HashMap in (key, value)  pair, and the value of that key is a dumpy object.
    And because the key is unique
    —> HashSet only contains unique elements.

Why HashSet can’t main the order of elements ?

  • Hash Set can not maintain the orders of elements because it uses the hash algorithm to implement and it uses HashMap to store the elements

    With  Hash Map, the key will be caculated by hash function and it returns the hashCode
    After that it store element in a bucket base on the hash code.
    —>  it can not maintain the order of elements added.

Leave a Reply

Your email address will not be published. Required fields are marked *