fc8da01f1ae01b9da077533f1b9abf9fbfeb2ec6
[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 import org.opendaylight.yangtools.concepts.Builder;
11
12 /**
13  * Utility class for incrementally building object hashCode by hashing together
14  * component objects, one by one.
15  *
16  * @param <T> Component objec type
17  */
18 public final class HashCodeBuilder<T> implements Builder<Integer> {
19     /**
20      *
21      * The value 31 was chosen because it is an odd prime. If it were even and the multiplication
22      * overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The
23      * advantage of using a prime is less clear, but it is traditional. A nice property of 31 is
24      * that the multiplication can be replaced by a shift and a subtraction for better performance:
25      * 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.
26      *
27      * (from Joshua Bloch's Effective Java, Chapter 3, Item 9: Always override hashcode when you
28      * override equals, page 48)
29      */
30     private static final int PRIME = 31;
31     private int currentHash;
32
33     /**
34      * Create a new instance, with internal hash initialized to 1,
35      * equivalent of <code>HashCodeBuilder(1)</code>.
36      */
37     public HashCodeBuilder() {
38         this(1);
39     }
40
41     /**
42      * Create a new instance, with internal hash set to specified seed.
43      *
44      * @param seedHash Seed hash value
45      */
46     public HashCodeBuilder(final int seedHash) {
47         this.currentHash = seedHash;
48     }
49
50     /**
51      * Determine the next hash code combining a base hash code and the
52      * hash code of an object.
53      *
54      * @param hashCode base hash code
55      * @param obj Object to be added
56      * @return Combined hash code
57      */
58     public static int nextHashCode(final int hashCode, final Object obj) {
59         return PRIME * hashCode + obj.hashCode();
60     }
61
62     /**
63      * Update the internal hash code with the hash code of a component
64      * object.
65      *
66      * @param obj Component object
67      */
68     public void addArgument(final T obj) {
69         currentHash = nextHashCode(currentHash, obj);
70     }
71
72     @Override
73     public Integer build() {
74         return currentHash;
75     }
76
77     @Deprecated
78     public Integer toInstance() {
79         return currentHash;
80     }
81 }