DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Curious about the future of data-driven systems? Join our Data Engineering roundtable and learn how to build scalable data platforms.

Data Engineering: The industry has come a long way from organizing unstructured data to adopting today's modern data pipelines. See how.

Threat Detection: Learn core practices for managing security risks and vulnerabilities in your organization — don't regret those threats!

Managing API integrations: Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

Trending

  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • AWS Redshift Data Sharing: Unlocking the Power of Collaborative Analytics
  • Securing Cloud-Native Applications: A CISO’s Perspective on Broken Access Control
  • Increase Model Flexibility and ROI for GenAI App Delivery With Kubernetes

Hash Code Generator

By 
Snippets Manager user avatar
Snippets Manager
·
May. 04, 07 · Code Snippet
Likes (0)
Comment
Save
Tweet
Share
7.8K Views

Join the DZone community and get the full member experience.

Join For Free
Simple hash code generator which allows hash codes for primitives and Java objects to be combined for a single object hash code with:

  new HashCode().hash(value1)
                .hash(value2)
                .hash(value3)
                .getHashCode();

This also supports hashing of arrays by recursively hashing all elements in the array.  Thanks to Item 8 in Joshua Bloch's "Effective Java" for the hash code theory:


public class HashCode {

    static final int DEFAULT_SEED = 23;
    static final int fODD_PRIME_NUMBER = 37;
    
    int hash;
    
    // ------------------------------------------------- Constructors
    
    /**
     * Constructor - creates a hash code object initialized with
     * the given seed value.
     */
    public HashCode(int seed) {
        this.hash = seed;
    }
    /**
     * Constructor - creates a hash code object initialized with
     * a default seed value.
     */
    public HashCode() {
        this(DEFAULT_SEED);
    }
    
    // ---------------------------------------------------- Accessors
    
    /**
     * Returns the hash code stored in the object
     */
    public int getHashCode() {
        return this.hash;
    }
    
    public String toString() {
        return String.valueOf(this.hash);
    }
    
    // ----------------------------------------------- Implementation
    
    /**
     * Adds the given value to the stored hash.  This is done by
     * multiplying the current hash by fODD_PRIME_NUMBER and then
     * adding the new value to it.
     */
    private void add(int value){
        this.hash = fODD_PRIME_NUMBER * this.hash + value;
    }
    
    //basic number types:
    
    public HashCode hash(int value) {
        add(value);
        return this;
    }
    public HashCode hash(long value) {
        add((int)( value ^ (value >>> 32) ));
        return this;
    }
    public HashCode hash(short value) {
        add((int)value);
        return this;
    }
    public HashCode hash(byte value) {
        add((int)value);
        return this;
    }
    public HashCode hash(float value ) {
        add(Float.floatToIntBits(value) );
        return this;
    }
    public HashCode hash(double value) {
        return hash(Double.doubleToLongBits(value));
    }
    
    //other primitives:
    
    public HashCode hash(boolean value) {
        add(value ? 1 : 0);
        return this;
    }
    public HashCode hash(char value) {
        add((int)value);
        return this;
    }
    
    //objects:
    
    /**
     * Hashes an object.  If this is null it will hash a value
     * of zero.  If it is an array it will recursively hash all
     * of the elements in the array.  For other objects it will
     * simply invoke their own hashCode() method.
     */
    public HashCode hash(Object obj) {
        
        if (obj == null) 
            add(0);
        
        else if (!isArray(obj) ) 
            add(obj.hashCode());
        
        else {
            //recursively hash all elements in the array
            int length = Array.getLength(obj);
            for (int i = 0; i < length; i++) {
                Object item = Array.get(obj, i);
                hash(item);
            }
        }
        
        return this;
    }
    
    // ----------------------------------------------- Static Methods
    
    /**
     * Returns true if the object is an array
     */
    private static boolean isArray(Object obj){
        return obj.getClass().isArray();
    }   
    
    /**
     * Returns a hash code for the given object.  This is offered
     * as a simplified method for:
     * 
     *   new HashCode().hash(obj).getHashCode()
     *   
     * Most notably, it allows for the quick and easy caching of
     * arrays.  It is not intended for hashing any arbitrary object
     * though.  For hashes beyond a single object property it is
     * better to instantiate the HashCode object and hash all
     * of the pertinent properties.
     */
    public static int hashArray(Object obj) {
        return new HashCode().hash(obj).getHashCode();
    }
    
    // ------------------------------------------------------ Testing
    
    public static void main(String [] args) {
        double [] a1 = new double [] {1,2,3,4,5,6};
        double [] a2 = new double [] {1,2,3,4,5,6};
        System.out.println(a1.hashCode());
        System.out.println(a2.hashCode());
        
        System.out.println(new HashCode().hash(a1));
        System.out.println(new HashCode().hash(a2));
    }
}

Opinions expressed by DZone contributors are their own.

Partner Resources


Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: