2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.util;
10 import org.opendaylight.yangtools.concepts.Builder;
13 * Utility class for incrementally building object hashCode by hashing together
14 * component objects, one by one.
16 * @param <T> Component objec type
18 public final class HashCodeBuilder<T> implements Builder<Integer> {
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.
27 * (from Joshua Bloch's Effective Java, Chapter 3, Item 9: Always override hashcode when you
28 * override equals, page 48)
30 private static final int PRIME = 31;
31 private int currentHash;
34 * Create a new instance, with internal hash initialized to 1,
35 * equivalent of <code>HashCodeBuilder(1)</code>.
37 public HashCodeBuilder() {
42 * Create a new instance, with internal hash set to specified seed.
44 * @param seedHash Seed hash value
46 public HashCodeBuilder(final int seedHash) {
47 this.currentHash = seedHash;
51 * Determine the next hash code combining a base hash code and the
52 * hash code of an object.
54 * @param hashCode base hash code
55 * @param obj Object to be added
56 * @return Combined hash code
58 public static int nextHashCode(final int hashCode, final Object obj) {
59 return PRIME * hashCode + obj.hashCode();
63 * Update the internal hash code with the hash code of a component
66 * @param obj Component object
68 public void addArgument(final T obj) {
69 currentHash = nextHashCode(currentHash, obj);
73 public Integer build() {