HashCode.java :  » Development » jodd » jodd » util » Java Open Source

Java Open Source » Development » jodd 
jodd » jodd » util » HashCode.java
// Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.

package jodd.util;

/**
 * Non-static implementation of {@link HashCodeUtil} for easier usage.
 */
public class HashCode {

  public int hashCode = 173;

  public int prime = 37;

  public HashCode() {
  }

  public HashCode(int seed) {
    this.hashCode = seed;
  }

  public HashCode(int seed, int prime) {
    this.hashCode = seed;
    this.prime = prime;
  }

  // ---------------------------------------------------------------- hashing

  /**
   * Calculate hash code for booleans.
   */
  public HashCode hash(boolean aBoolean) {
    hashCode = (prime * hashCode) + (aBoolean ? 1 : 0);
    return this;
  }

  /**
   * Calculate hash code for chars.
   */
  public HashCode hash(char aChar) {
    hashCode = (prime * hashCode) + (int) aChar;
    return this;
  }

  /**
   * Calculate hash code for ints.
   */
  public HashCode hash(int aInt) {
    hashCode = (prime * hashCode) + aInt;
    return this;
  }

  /**
   * Calculate hash code for longs.
   */
  public HashCode hash(long aLong) {
    hashCode = (prime * hashCode) + (int) (aLong ^ (aLong >>> 32));
    return this;
  }

  /**
   * Calculate hash code for floats.
   */
  public HashCode hash(float aFloat) {
    return hash(Float.floatToIntBits(aFloat));
  }

  /**
   * Calculate hash code for doubles.
   */
  public HashCode hash(double aDouble) {
    return hash(Double.doubleToLongBits(aDouble));
  }

  /**
   * Calculate hash code for Objects. Object is a possibly-null object field, and possibly an array.
   * <p>
   * If <code>aObject</code> is an array, then each element may be a primitive
   * or a possibly-null object.
   */
  public HashCode hash(Object aObject) {
    if (aObject == null) {
      hash(0);
    } else if (aObject.getClass().isArray() == false) {
      hash(aObject.hashCode());
    } else {
      Object[] objects = (Object[]) aObject;
      int length = objects.length;
      for (int idx = 0; idx < length; ++idx) {
        hash(objects[idx]);
      }
    }
    return this;
  }


  // ---------------------------------------------------------------- hash code

  public int getHashCode() {
    return hashCode;
  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.