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