1 package org.saf.struts.util;
2
3 import java.lang.reflect.Array;
4
5
6 /***
7 * Collected methods which allow easy implementation of hashCode.
8 *
9 *
10 * Example use case: *
11 *
12 * public int hashCode() {
13 * int result = HashCodeUtil.SEED;
14 * //collect the contributions of various fields
15 * result = HashCodeUtil.hash(result, fPrimitive);
16 * result = HashCodeUtil.hash(result, fObject);
17 * result = HashCodeUtil.hash(result, fArray);
18 * return result;
19 * }
20 *
21 * @author Wim Tobback
22 * @version 1.0
23 * @since 1.0
24 */
25 public final class HashCodeUtil {
26 public static final int SEED = 47;
27 private static final int fODD_PRIME_NUMBER = 37;
28
29 public static int hash(int seed, Object aObject) {
30 int result = seed;
31
32 if (aObject == null) {
33 result = hash(result, 0);
34 } else if (!isArray(aObject)) {
35 result = hash(result, aObject.hashCode());
36 } else {
37 int length = Array.getLength(aObject);
38
39 for (int idx = 0; idx < length; ++idx) {
40 Object item = Array.get(aObject, idx);
41 result = hash(result, item);
42 }
43 }
44
45 return result;
46 }
47
48 public static int hash(int seed, boolean aBoolean) {
49 return firstTerm(seed) + (aBoolean ? 1 : 0);
50 }
51
52 public static int hash(int seed, char aChar) {
53 return firstTerm(seed) + (int) aChar;
54 }
55
56 public static int hash(int seed, int aInt) {
57 return firstTerm(seed) + aInt;
58 }
59
60 public static int hash(int seed, long aLong) {
61 return firstTerm(seed) + (int) (aLong ^ (aLong >>> 32));
62 }
63
64 public static int hash(int seed, float aFloat) {
65 return hash(seed, Float.floatToIntBits(aFloat));
66 }
67
68 public static int hash(int seed, double aDouble) {
69 return hash(seed, Double.doubleToLongBits(aDouble));
70 }
71
72 private static boolean isArray(Object aObject) {
73 return aObject.getClass().isArray();
74 }
75
76 private static int firstTerm(int seed) {
77 return fODD_PRIME_NUMBER * seed;
78 }
79 }