Skip to content

Commit d53f432

Browse files
committed
core: Opaque: Clarify behavior of equals/hashCode
Let's make sure subclasses get that right. We cannot provide a "default" implementation for methods in java.lang.Object, so let's provide static default helpers. Related: #149 Signed-off-by: Christian Kohlschütter <[email protected]>
1 parent ff66e69 commit d53f432

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

core/src/main/java/org/dcache/nfs/util/Opaque.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,66 @@ public static Opaque forBytes(ByteBuffer buf, int length) {
5252
return new OpaqueImpl(bytes);
5353
}
5454

55+
/**
56+
* Default implementation for {@link #hashCode()}.
57+
*
58+
* @param obj The instance object.
59+
* @return The hash code.
60+
* @see #hashCode()
61+
*/
62+
public static int defaultHashCode(Opaque obj) {
63+
return Arrays.hashCode(obj.toBytes());
64+
}
65+
66+
/**
67+
* Default implementation for {@link #equals(Object)}.
68+
*
69+
* @param obj The instance object.
70+
* @param other The other object.
71+
* @return {@code true} if equal.
72+
* @see #equals(Object)
73+
*/
74+
public static boolean defaultEquals(Opaque obj, Object other) {
75+
if (other == obj) {
76+
return true;
77+
}
78+
if (!(other instanceof Opaque)) {
79+
return false;
80+
}
81+
return Arrays.equals(obj.toBytes(), ((Opaque) other).toBytes());
82+
}
83+
84+
/**
85+
* Returns a byte-representation of this opaque object.
86+
*
87+
* @return A new array.
88+
*/
5589
byte[] toBytes();
5690

91+
/**
92+
* Returns a Base64 string representing this opaque object.
93+
*
94+
* @return A Base64 string.
95+
*/
5796
String toBase64();
5897

98+
/**
99+
* Returns the hashCode based on the byte-representation of this instance.
100+
* <p>
101+
* This method must behave like {@link #defaultHashCode(Opaque)}, but may be optimized.
102+
*
103+
* @return The hashCode.
104+
*/
59105
@Override
60106
int hashCode();
61107

108+
/**
109+
* Compares this object to another one.
110+
* <p>
111+
* This method must behave like {@link #defaultEquals(Opaque, Object)}, but may be optimized.
112+
*
113+
* @return {@code true} if both objects are equal.
114+
*/
62115
@Override
63116
boolean equals(Object o);
64117

0 commit comments

Comments
 (0)