Take the 2-minute tour ×

I am writing a test cases where I need to meaningful compare two objects which do not implement equals. I don't want to write equals or hashcode methods for these objects.

Is there an API which can do this for me?

share|improve this question
Do you mean you don't want to write an equals method in that class or you don't want to write the code at all? –  Jon Skeet Aug 30 '11 at 6:12
Define meaningful ... –  Thilo Aug 30 '11 at 6:13
Use assertSame() if you want to compare if these two references refers to the same (one) object. Anyway, you should implement equals if you want to test equality - Java is object oriented and that's how it should be done. –  Piotrek De Aug 30 '11 at 6:15
Developers still wait for a breakthrough in the research of do-what-I-mean algorithms ... a patent is worth a billion dollars ;) –  Andreas_D Aug 30 '11 at 6:20
It's difficult to determine what do you mean by "compare two objects". do you want to compare two instances of the same object, or two instances of different objects or... ? –  Krystian Aug 30 '11 at 7:23
add comment

4 Answers

Yes there is look up the use of a comparator which should suit your needs perfectly.

A link to the JAVA API Interface Comparator

And a link to a blog post explaining how to use it. Comparable and Comparator interfaces-Part 2

share|improve this answer
add comment

If it's just for test code you could just create a helper method to encapsulate your assertions:

public static void assertMyClassEquals(MyClass expected, MyClass actual) {
    assertEquals(expected.foo, actual.foo);

But I'm not sure I understand your aversion to creating an equals() method which could obviously be useful.

share|improve this answer
+1. And if the meaningfulness of the method extends beyond the usefulness in a test case, you can make it part of the application code itself (rather than the test suite). –  Thilo Aug 30 '11 at 6:14
add comment

Apache commons-lang has an automatic equals builder - e.g. "reflection-equals". API documentation for EqualsBilder. Also note that there is a HashCodeBuilder in the same library.

Example using this library:

static class A {
    private int a;
    private String b;
    A(int a, String b) {
        this.a = a;
        this.b = b;

public static void main(String[] args) {
    A a1 = new A(123, "Hello World!");
    A a2 = new A(321, "Hello!");
    A a3 = new A(123, "Hello World!");

    System.out.println(EqualsBuilder.reflectionEquals(a1, a2, true));
    System.out.println(EqualsBuilder.reflectionEquals(a1, a3, true));


share|improve this answer
add comment

Sometimes comparing the result of toString is a meaningful comparison.

share|improve this answer
The OP said he didnt want to implement his own hashcode method, which is pretty much what Objects toString method does. –  user439407 Aug 30 '11 at 7:07
add comment

Your Answer


