BUG-4803: make MutableOffsetMap abstract
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / HashCodeBuilder.java
index 874809f13c77e74dba17f1fa21ed9e1877ef64d1..f629ee53a9bdbf0679f4a3b6165c86b2f07914b8 100644 (file)
@@ -16,11 +16,23 @@ import org.opendaylight.yangtools.concepts.Builder;
  * @param <T> Component objec type
  */
 public final class HashCodeBuilder<T> implements Builder<Integer> {
+    /**
+     *
+     * The value 31 was chosen because it is an odd prime. If it were even and the multiplication
+     * overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The
+     * advantage of using a prime is less clear, but it is traditional. A nice property of 31 is
+     * that the multiplication can be replaced by a shift and a subtraction for better performance:
+     * 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.
+     *
+     * (from Joshua Bloch's Effective Java, Chapter 3, Item 9: Always override hashcode when you
+     * override equals, page 48)
+     */
+    private static final int PRIME = 31;
     private int currentHash;
 
     /**
      * Create a new instance, with internal hash initialized to 1,
-     * equivalent of {@link #HashCodeBuilder(1)}.
+     * equivalent of <code>HashCodeBuilder(1)</code>.
      */
     public HashCodeBuilder() {
         this(1);
@@ -44,7 +56,7 @@ public final class HashCodeBuilder<T> implements Builder<Integer> {
      * @return Combined hash code
      */
     public static int nextHashCode(final int hashCode, final Object obj) {
-        return 31 * hashCode + obj.hashCode();
+        return PRIME * hashCode + obj.hashCode();
     }
 
     /**
@@ -58,7 +70,7 @@ public final class HashCodeBuilder<T> implements Builder<Integer> {
     }
 
     @Override
-    public Integer toInstance() {
+    public Integer build() {
         return currentHash;
     }
 }