IDKey.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.lang3.builder;

  18. // adapted from org.apache.axis.utils.IDKey

  19. /**
  20.  * Wrap an identity key (System.identityHashCode()) so that an object can only be equal() to itself.
  21.  *
  22.  * This is necessary to disambiguate the occasional duplicate identityHashCodes that can occur.
  23.  */
  24. final class IDKey {

  25.     private final Object value;
  26.     private final int id;

  27.     /**
  28.      * Constructs new instance.
  29.      *
  30.      * @param value The value
  31.      */
  32.     IDKey(final Object value) {
  33.         // This is the Object hash code
  34.         this.id = System.identityHashCode(value);
  35.         // There have been some cases (LANG-459) that return the
  36.         // same identity hash code for different objects. So
  37.         // the value is also added to disambiguate these cases.
  38.         this.value = value;
  39.     }

  40.     /**
  41.      * Tests if instances are equal.
  42.      *
  43.      * @param other The other object to compare to
  44.      * @return if the instances are for the same object
  45.      */
  46.     @Override
  47.     public boolean equals(final Object other) {
  48.         if (!(other instanceof IDKey)) {
  49.             return false;
  50.         }
  51.         final IDKey idKey = (IDKey) other;
  52.         if (id != idKey.id) {
  53.             return false;
  54.         }
  55.         // Note that identity equals is used.
  56.         return value == idKey.value;
  57.     }

  58.     /**
  59.      * Gets the hash code, the system identity hash code.
  60.      *
  61.      * @return the hash code.
  62.      */
  63.     @Override
  64.     public int hashCode() {
  65.         return id;
  66.     }
  67. }