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.eclipse.jdt.annotation.NonNull;
11 import org.opendaylight.yangtools.concepts.Builder;
14 * Utility class for incrementally building object hashCode by hashing together component objects, one by one.
16 * @param <T> Component object type
18 public final class HashCodeBuilder<T> implements Builder<Integer> {
20 * The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed,
21 * information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is
22 * less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift
23 * and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization
26 * <p>(from Joshua Bloch's Effective Java, Chapter 3, Item 9: Always override hashcode when you override equals,
29 private static final int PRIME = 31;
30 private int currentHash;
33 * Create a new instance, with internal hash initialized to 1, equivalent of <code>HashCodeBuilder(1)</code>.
35 public HashCodeBuilder() {
40 * Create a new instance, with internal hash set to specified seed.
42 * @param seedHash Seed hash value
44 public HashCodeBuilder(final int seedHash) {
45 this.currentHash = seedHash;
49 * Determine the next hash code combining a base hash code and the hash code of an object.
51 * @param hashCode base hash code
52 * @param obj Object to be added
53 * @return Combined hash code
55 public static int nextHashCode(final int hashCode, final Object obj) {
56 return PRIME * hashCode + obj.hashCode();
60 * Update the internal hash code with the hash code of a component object.
62 * @param obj Component object
64 public void addArgument(final T obj) {
65 currentHash = nextHashCode(currentHash, obj);
69 public @NonNull Integer build() {