j.u.Objects follow-up: deepEquals(Object, Object)?
Eamonn McManus
Eamonn.McManus at Sun.COM
Fri Oct 9 09:30:33 UTC 2009
Joseph D. Darcy wrote:
> What are scenarios where this method would be used?
I use a similar method fairly often in unit tests. JUnit's assertEquals doesn't
do the right thing if its arguments happen to be arrays, so I use the following
simple if inefficient implementation:
static void deepEquals(Object x, Object y) {
return Arrays.deepEquals(new Object[] {x}, new Object[] {y});
}
What that shows of course is that the messy logic you mention is already present in
Arrays.deepEquals so you could factor it out.
Regards,
Éamonn McManus · JMX Spec Lead · http://weblogs.java.net/blog/emcmanus
Joseph D. Darcy wrote:
> Another piece of functionality requested in the j.u.Objects thread was a
> deepEquals(Object a, Object b.) method that "did the right thing" if the
> arguments happened to dynamically be arrays.
>
> I've been thinking a bit how this might be implemented.
>
> The array-ness of a and b would need to be determined, after any
> up-front null-checks
>
> boolean aIsArray = a.getClass().isArray();
> boolean bIsArray = b.getClass().isArray();
>
> followed various case-analyses.
>
> if (aIsArray && bIsArray) {
> Class<?> aComponentType = a.getClass().getComponentType();
> Class<?> bComponentType = b.getClass().getComponentType();
> if (aComponentType == bComponentType) {
> // long case analysis to cast and call Arrays.deepEquals if
> ComponentType is a reference type
> // or the matching Arrays.equals(primitiveComponent[],
> primitiveComponent[]) method if
> // aComponentType.isPrimitive().
> } else
> return false;
> } else
> return a.equals(b);
>
> Certainly a bit messy internally.
>
> What are scenarios where this method would be used?
>
> -Joe
More information about the core-libs-dev
mailing list