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 * https://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
18 package org.apache.commons.lang3.builder;
19
20 // adapted from org.apache.axis.utils.IDKey
21
22 /**
23 * Wrap an identity key (System.identityHashCode()) so that an object can only be equal() to itself.
24 *
25 * This is necessary to disambiguate the occasional duplicate identityHashCodes that can occur.
26 */
27 final class IDKey {
28
29 private final Object value;
30 private final int id;
31
32 /**
33 * Constructs new instance.
34 *
35 * @param value The value
36 */
37 IDKey(final Object value) {
38 // This is the Object hash code
39 this.id = System.identityHashCode(value);
40 // There have been some cases (LANG-459) that return the
41 // same identity hash code for different objects. So
42 // the value is also added to disambiguate these cases.
43 this.value = value;
44 }
45
46 /**
47 * Tests if instances are equal.
48 *
49 * @param other The other object to compare to
50 * @return if the instances are for the same object
51 */
52 @Override
53 public boolean equals(final Object other) {
54 if (!(other instanceof IDKey)) {
55 return false;
56 }
57 final IDKey idKey = (IDKey) other;
58 if (id != idKey.id) {
59 return false;
60 }
61 // Note that identity equals is used.
62 return value == idKey.value;
63 }
64
65 /**
66 * Gets the hash code, the system identity hash code.
67 *
68 * @return the hash code.
69 */
70 @Override
71 public int hashCode() {
72 return id;
73 }
74 }