View Single Post
  #4 (permalink)  
Old 08-03-2007, 04:05 PM
brianhks brianhks is offline
Senior Member
 
Join Date: Jul 2007
Posts: 134
brianhks will become famous soon enough
Hashtable, HashSet, HashMap; they all use a hash to store the objects.

Code:
k1.i=2;
Just so you understand, the above line of code is evil. You are changing the hash value of an object that has already been placed in the Set. If you place an object in a HashSet and then change its hash code the object will get lost. Because later when you try to remove it the HashSet will go looking in the wrong bucket for the object and not find it.

Equals is only called if the bucket into which the object is being placed already contains an object. Now as for why equals is called intermittently. My suspicion is that when comparing objects they first use the '=' to see if they are in fact the same object before calling .equals(). Notice that the equals is only called when you change the value of k1 to equal k2 and then try to remove k1. Because k1 has the value of k2 it will remove k2 from the Set but k1 = k2 is not true so it will call k1.equals(k2).
Reply With Quote