01: // Copyright (c) 1999 CERN - European Organization for Nuclear Research.
02:
03: // Permission to use, copy, modify, distribute and sell this software and
04: // its documentation for any purpose is hereby granted without fee,
05: // provided that the above copyright notice appear in all copies and that
06: // both that copyright notice and this permission notice appear in
07: // supporting documentation. CERN makes no representations about the
08: // suitability of this software for any purpose. It is provided "as is"
09: // without expressed or implied warranty.
10:
11: package gnu.trove;
12:
13: /**
14: * Provides various hash functions.
15: *
16: * @author wolfgang.hoschek@cern.ch
17: * @version 1.0, 09/24/99
18: */
19: public final class HashFunctions {
20: /**
21: * Returns a hashcode for the specified value.
22: *
23: * @return a hash code value for the specified value.
24: */
25: public static int hash(double value) {
26: assert !Double.isNaN(value) : "Values of NaN are not supported.";
27:
28: long bits = Double.doubleToLongBits(value);
29: return (int) (bits ^ (bits >>> 32));
30: //return (int) Double.doubleToLongBits(value*663608941.737);
31: //this avoids excessive hashCollisions in the case values are
32: //of the form (1.0, 2.0, 3.0, ...)
33: }
34:
35: /**
36: * Returns a hashcode for the specified value.
37: *
38: * @return a hash code value for the specified value.
39: */
40: public static int hash(float value) {
41: assert !Float.isNaN(value) : "Values of NaN are not supported.";
42:
43: return Float.floatToIntBits(value * 663608941.737f);
44: // this avoids excessive hashCollisions in the case values are
45: // of the form (1.0, 2.0, 3.0, ...)
46: }
47:
48: /**
49: * Returns a hashcode for the specified value.
50: *
51: * @return a hash code value for the specified value.
52: */
53: public static int hash(int value) {
54: // Multiply by prime to make sure hash can't be negative (see Knuth v3, p. 515-516)
55: return value * 31;
56: }
57:
58: /**
59: * Returns a hashcode for the specified value.
60: *
61: * @return a hash code value for the specified value.
62: */
63: public static int hash(long value) {
64: // Multiply by prime to make sure hash can't be negative (see Knuth v3, p. 515-516)
65: return ((int) (value ^ (value >>> 32))) * 31;
66: }
67:
68: /**
69: * Returns a hashcode for the specified object.
70: *
71: * @return a hash code value for the specified object.
72: */
73: public static int hash(Object object) {
74: return object == null ? 0 : object.hashCode();
75: }
76: }
|