Information Technology Reference
In-Depth Information
return name.GetHashCode();
}
}
Suppose that you execute the following code snippet:
Customer c1 = new Customer ( "Acme Products" );
myHashMap.Add(c1, orders);
// Oops, the name is wrong:
c1.Name = "Acme Software";
c1 is lost somewhere in the hash map. When you placed c1 in the map, the
hash code was generated from the string "Acme Products". After you
change the name of the customer to "Acme Software", the hash code value
changed. It's now being generated from the new name: "Acme Software".
c1 is stored in the bucket defined by "Acme Products", but it should be in
the bucket defined for "Acme Software". You've lost that customer in your
own collection. It's lost because the hash code is not an object invariant.
Yo u ' v e c h a n g e d t h e c o r r e c t b u c k e t a f t e r s t o r i n g t h e o b j e c t .
The earlier situation can occur only if Customer is a reference type. Value
types misbehave differently, but they still cause problems. If customer is a
value type, a copy of c1 gets stored in the hash map. The last line chang-
ing the value of the name has no effect on the copy stored in the hash map.
Because boxing and unboxing make copies as well, it's very unlikely that
you can change the members of a value type after that object has been
added to a collection.
The only way to address rule 2 is to define the hash code function to return
a value based on some invariant property or properties of the object.
System.Object abides by this rule using the object identity, which does not
change. System.ValueType hopes that the first field in your type does not
change. You can't do better without making your type immutable. When
you define a value type that is intended for use as a key type in a hash con-
tainer, it must be an immutable type. If you violate this recommendation,
then the users of your type will find a way to break hashtables that use
your type as keys. Revisiting the Customer class, you can modify it so that
the customer name is immutable. The highlight shows the changes to
make a customer's name immutable:
public class Customer
{
Search WWH ::




Custom Search