KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > HashCodeUtil


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.util;
4
5 /**
6  * Collected methods which allow easy implementation of <code>hashCode()</code>.
7  * Based on items 7 and 8 from "Effective Java" book.
8  * <p>
9  * Usage scenarion:<br>
10  * <pre>
11  * int result = HashCodeUtil.SEED;
12  * result = HashCodeUtil.hash(result, fIsDecrepit);
13  * ...
14  * </pre>
15  *
16  * todo: Add primitive arrays.
17  */

18 public class HashCodeUtil {
19
20     /**
21      * An initial hash code value to which is added contributions from fields.
22      * Using a non-zero value decreases collisons of hash code values.
23      */

24     public static final int SEED = 173;
25
26     public static final int PRIME = 37;
27
28     /**
29      * Calculate hash code for booleans.
30      */

31     public static int hash(int seed, boolean aBoolean) {
32         return (PRIME * seed) + (aBoolean ? 1 : 0);
33     }
34
35     /**
36      * Calculate hash code for chars.
37      */

38     public static int hash(int seed, char aChar) {
39         return (PRIME * seed) + (int) aChar;
40     }
41
42     /**
43      * Calculate hash code for ints.
44      */

45     public static int hash(int seed, int aInt) {
46         return (PRIME * seed) + aInt;
47     }
48
49     /**
50      * Calculate hash code for longs.
51      */

52     public static int hash(int seed, long aLong) {
53         return (PRIME * seed) + (int) (aLong ^ (aLong >>> 32));
54     }
55
56     /**
57      * Calculate hash code for floats.
58      */

59     public static int hash(int seed, float aFloat) {
60         return hash(seed, Float.floatToIntBits(aFloat));
61     }
62
63     /**
64      * Calculate hash code for doubles.
65      */

66     public static int hash(int seed, double aDouble) {
67         return hash(seed, Double.doubleToLongBits(aDouble));
68     }
69
70     /**
71      * Calculate hash code for Objects. Object is a possibly-null object field, and possibly an array.
72      * <p>
73      * If <code>aObject</code> is an array, then each element may be a primitive
74      * or a possibly-null object.
75      */

76     public static int hash(int seed, Object JavaDoc aObject) {
77         int result = seed;
78         if (aObject == null) {
79             result = hash(result, 0);
80         } else if (aObject.getClass().isArray() == false) {
81             result = hash(result, aObject.hashCode());
82         } else {
83             Object JavaDoc[] objects = (Object JavaDoc[]) aObject;
84             int length = objects.length;
85             for (int idx = 0; idx < length; ++idx) {
86                 result = hash(result, objects[idx]);
87             }
88         }
89         return result;
90     }
91
92 }
Popular Tags