View Javadoc
1   /**
2    * @(#)HashCodeUtil.java
3    * Copyright (C) 2008-2011 delhezi.com
4    *
5    * This class is released under the:
6    * GNU Lesser General Public License (LGPL) version 3 or later.
7    * http://www.gnu.org/copyleft/lesser.html
8    */
9   package com.delhezi.ga.utility;
10  
11  import org.apache.log4j.Logger;
12  import java.lang.reflect.Array;
13  
14  /**
15   * Created by Rafal Gorzkowski
16   * User: rafal
17   * Date: 20.01.11
18   * Time: 0:43
19   */
20  
21  public final class HashCodeUtil {
22  
23      static private final Logger log = Logger.getLogger(HashCodeUtil.class);
24      static private final int ODD_PRIME_NUMBER = 31;
25  
26      static public final int SEED = 17;
27  
28  
29      public static int hash(int aSeed, boolean aBoolean) {
30          log.debug("hash for boolean");
31          return firstElement(aSeed) + (aBoolean ? 1 : 0);
32      }
33  
34      public static int hash(int aSeed, char aChar) {
35          log.debug("hash for char");
36          return firstElement(aSeed) + (int) aChar;
37      }
38  
39      public static int hash(int aSeed, int aInt) {
40          log.debug("hash for int");
41          return firstElement(aSeed) + aInt;
42      }
43  
44      public static int hash(int aSeed, long aLong) {
45          log.debug("hash for long");
46          return firstElement(aSeed) + (int) (aLong ^ (aLong >>> 32));
47      }
48  
49      public static int hash(int aSeed, float aFloat) {
50          log.debug("hash for float");
51          return hash(aSeed, Float.floatToIntBits(aFloat));
52      }
53  
54      public static int hash(int aSeed, double aDouble) {
55          log.debug("hash for double");
56          return hash(aSeed, Double.doubleToLongBits(aDouble));
57      }
58  
59      public static int hash(int aSeed, Object aObject) {
60          log.debug("hash for Object");
61          int result = aSeed;
62          if (aObject == null) {
63              result = hash(result, 0);
64          } else if (!isArray(aObject)) {
65              result = hash(result, aObject.hashCode());
66          } else {
67              int length = Array.getLength(aObject);
68              for (int index = 0; index < length; index++) {
69                  Object item = Array.get(aObject, index);
70                  result = hash(result, item);
71              }
72          }
73          return result;
74      }
75  
76      private static int firstElement(int aSeed) {
77          return ODD_PRIME_NUMBER * aSeed;
78      }
79  
80      private static boolean isArray(Object aObject) {
81          return aObject.getClass().isArray();
82      }
83  }