KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > HashCode


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

3 package jodd.util;
4
5 /**
6  * Non-static implementation of {@link HashCodeUtil} for easier usage.
7  */

8 public class HashCode {
9
10     public int hashCode = 173;
11
12     public int prime = 37;
13
14     public HashCode() {
15     }
16
17     public HashCode(int seed) {
18         this.hashCode = seed;
19     }
20
21     public HashCode(int seed, int prime) {
22         this.hashCode = seed;
23         this.prime = prime;
24     }
25
26     // ---------------------------------------------------------------- hashing
27

28     /**
29      * Calculate hash code for booleans.
30      */

31     public HashCode hash(boolean aBoolean) {
32         hashCode = (prime * hashCode) + (aBoolean ? 1 : 0);
33         return this;
34     }
35
36     /**
37      * Calculate hash code for chars.
38      */

39     public HashCode hash(char aChar) {
40         hashCode = (prime * hashCode) + (int) aChar;
41         return this;
42     }
43
44     /**
45      * Calculate hash code for ints.
46      */

47     public HashCode hash(int aInt) {
48         hashCode = (prime * hashCode) + aInt;
49         return this;
50     }
51
52     /**
53      * Calculate hash code for longs.
54      */

55     public HashCode hash(long aLong) {
56         hashCode = (prime * hashCode) + (int) (aLong ^ (aLong >>> 32));
57         return this;
58     }
59
60     /**
61      * Calculate hash code for floats.
62      */

63     public HashCode hash(float aFloat) {
64         return hash(Float.floatToIntBits(aFloat));
65     }
66
67     /**
68      * Calculate hash code for doubles.
69      */

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

80     public HashCode hash(Object JavaDoc aObject) {
81         if (aObject == null) {
82             hash(0);
83         } else if (aObject.getClass().isArray() == false) {
84             hash(aObject.hashCode());
85         } else {
86             Object JavaDoc[] objects = (Object JavaDoc[]) aObject;
87             int length = objects.length;
88             for (int idx = 0; idx < length; ++idx) {
89                 hash(objects[idx]);
90             }
91         }
92         return this;
93     }
94
95
96     // ---------------------------------------------------------------- hash code
97

98     public int getHashCode() {
99         return hashCode;
100     }
101
102 }
103
Popular Tags