650c00e15043ee43a99709bec8047c30bddd77d4
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / HashCodeBuilder.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.util;
9
10 /**
11  * Utility class for incrementally building object hashCode by hashing together component objects, one by one.
12  *
13  * @param <T> Component object type
14  */
15 public final class HashCodeBuilder<T> {
16     /**
17      * The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed,
18      * information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is
19      * less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift
20      * and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization
21      * automatically.
22      *
23      * <p>(from Joshua Bloch's Effective Java, Chapter 3, Item 9: Always override hashcode when you override equals,
24      * page 48)
25      */
26     private static final int PRIME = 31;
27     private int currentHash;
28
29     /**
30      * Create a new instance, with internal hash initialized to 1, equivalent of <code>HashCodeBuilder(1)</code>.
31      */
32     public HashCodeBuilder() {
33         this(1);
34     }
35
36     /**
37      * Create a new instance, with internal hash set to specified seed.
38      *
39      * @param seedHash Seed hash value
40      */
41     public HashCodeBuilder(final int seedHash) {
42         this.currentHash = seedHash;
43     }
44
45     /**
46      * Determine the next hash code combining a base hash code and the hash code of an object.
47      *
48      * @param hashCode base hash code
49      * @param obj Object to be added
50      * @return Combined hash code
51      */
52     public static int nextHashCode(final int hashCode, final Object obj) {
53         return PRIME * hashCode + obj.hashCode();
54     }
55
56     /**
57      * Update the internal hash code with the hash code of a component object.
58      *
59      * @param obj Component object
60      */
61     public void addArgument(final T obj) {
62         currentHash = nextHashCode(currentHash, obj);
63     }
64
65     /**
66      * Return the currently-accumulated hash code.
67      *
68      * @return Current hash code
69      */
70     public int build() {
71         return currentHash;
72     }
73 }