![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e57. Comparing Object Values Using Hash CodesThe hash code of an object is an integer value that's computed using the value of the object. For example, for aString object, the
characters of the string are used to compute the hash code. For an
Integer object, the integer value is used to compute the hash code.
Hash codes are typically used as an efficient way of comparing
the values of two objects. For example, if the hash code of the
string If the hash codes of two object values are different, the
object values are guaranteed to be different. However, if the hash
codes of two object values are the same, the object values are
not guaranteed to be the same. An additional call to
The ` File file1 = new File("a"); File file2 = new File("a"); File file3 = new File("b"); // Get the hash codes int hc1 = file1.hashCode(); // 1234416 int hc2 = file2.hashCode(); // 1234416 int hc3 = file3.hashCode(); // 1234419 // Check if two object values are the same if (hc1 == hc2 && file1.equals(file2)) { // They are the same } // Get the identity hash codes int ihc1 = System.identityHashCode(file1); // 1027049 int ihc2 = System.identityHashCode(file2); // 14642381 int ihc3 = System.identityHashCode(file3); // 6298545
e58. Wrapping a Primitive Type in a Wrapper Object
© 2002 Addison-Wesley. |