Forum Stats

  • 3,837,920 Users
  • 2,262,309 Discussions
  • 7,900,433 Comments

Discussions

HashSet and Duplicate Entry

user575089
user575089 Member Posts: 466
edited Apr 27, 2018 12:10PM in Java Programming

HashSet does not allow duplicate entries.

Question :

What does duplicate would mean here when we talk about instances?  (Say Employee class)

does duplicate would mean only the address of the two instances is same ?

OR

does duplicate would mean the address and property values of the two instances are same?

OR

does duplicate would mean only the property values of the two instances are same?

I'm confused as what is duplicate to HashSet when we talk about instances. which one would be correct in above case?

Answers

  • Unknown
    edited Apr 27, 2018 12:10PM
    HashSet does not allow duplicate entries.Question :What does duplicate would mean here when we talk about instances? (Say Employee class)

    It means the KEY value can't be a duplicate.

    The Java API doc for HashMap (which is what HashSet is based on) says this

    https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#put-K-V-

    put

    public V put(K key, V value)

    Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

    You can EASILY test the results yourself.

    1. construct two instances of an object

    2. do a 'put' of the first instance reference as the key and using 'first put' as the value

    3. do a 'put' of the second instance reference as the key and using 'second put' as the value

    4. do a 'get' using the first instance as the key - what value was returned?

    5. do a 'get' using the second instance as the key - what value was returned?

    The BEST, and usually fastest, way to get an answer to 'what happens if I ..' questions is: TRY IT AND SEE!

This discussion has been closed.