-1

I have desperate doubt on following:

let's say I create

hashset<employee> set = new hashSet();
employee e1 = new employee("adithyan",1);
employee e2 = new employee("santhosh",1);
employee e3 = new employee("pavan",2);

set.add(e1);

--- e1 is object how hashtable generates unique hashcode for this and how this object will be stored in hashtable as we know hashtable will store key and value pair

set.add(e2);

-- let's say e1 and e2 hashcode are same and value gets stored in same bucket and if I do search on id=1, how it will search because e1 and e2 hashcodes are same, probably e1 and e2 would be stored in same bucket, what would be the result for this?

I am confused with bucketing which has more than one objects along with objects has same data(let's say bucket1->object1.city=bglr,object2.city.=bglr)- in this case hashcode will be the same because both objects are in same bucket, I don't know how searching would work!

can somebody explain how hashset uses hastable with same hashcode and bucketing concept?

shmosel
  • 49,289
  • 6
  • 73
  • 138
adithyan .p
  • 121
  • 1
  • 3
  • 12
  • First of all, HashSet uses HashMap not HashTable. Second of all, both hashCode and equals are used in the search for a key in the map/element in the set. – Eran Jan 12 '17 at 09:59
  • Possible duplicate of [How does a Java HashMap handle different objects with the same hash code?](http://stackoverflow.com/questions/6493605/how-does-a-java-hashmap-handle-different-objects-with-the-same-hash-code) – shmosel Jan 12 '17 at 10:03
  • HashSet uses hashtable in background – adithyan .p Jan 12 '17 at 10:19
  • I red from http://stackoverflow.com/questions/24742878/how-hashset-works-with-regards-to-hashcode, correct me if I am wrong – adithyan .p Jan 12 '17 at 10:21

1 Answers1

0

HashMap and HashSet work by using the hashCode method to determine in which bucket to store a value. When you add a new value, it will find the correct bucket and check all the values in that bucket with equals to make sure what you are adding isn't a duplicate.

When getting a value, it will check the corresponding bucket (based on hashCode again) and then do an equals call to make sure it really is the value you're looking for.

If you redefined equals and hashCode methods for Employee to match by id only, then e2 will be considered a duplicate and it will replace the previous value, even though that may not be what you want. In other words, the behaviour of the HashMap is defined by how you implemented hashCode and equals.

john16384
  • 7,800
  • 2
  • 30
  • 44