3

In python we can compare object by attributes by this method:

def __eq__(self, other): 
    return self.__dict__ == other.__dict__

It allows us to compare objects by their attributes no matter how many attributes they have.

Is something like this possible in Java? I tried to compare objects in this way, but you have to compare them by every attribute. Is it possible to do it similarly to Python eq method above?

public class MyClass {

public MyClass(attr1, attr2, attr3, attr4) {
    this.attr1 = attr1;
    this.attr2 = attr2;
    this.attr3 = attr3;
    this.attr4 = attr4;
}
public boolean equals(Object object2) {

    return object2 instanceof MyClass && 
attr1.equals(((MyClass)object2).attr1)&&......;
}
}
JeyKey
  • 413
  • 1
  • 9
  • 22
  • If hardcoding is not an option, it might make sense to store your attributes in a hashmap. I believe those util classes have methods to perform element wise comparisons... – cs95 Sep 10 '17 at 09:13
  • @cᴏʟᴅsᴘᴇᴇᴅ Could you show me how to do that? – JeyKey Sep 10 '17 at 09:14
  • Err... never mind. Apex (very similar to Java) hashmaps do have this feature, [java hashmaps don't](https://stackoverflow.com/questions/4082416/equality-between-2-hashmap). – cs95 Sep 10 '17 at 09:16

1 Answers1

2

If you want to write general method that handles every type, you need to use reflection. If you just want to do this with a type or two, then I suggest you override the equals method for each individual type i.e. hardcoding it.

Here's how you write a generic method that accepts every single type and compares the fields for equality:

private static <T> boolean allFieldsEqual(T a, T b) throws IllegalAccessException {
    Class<?> clazz = a.getClass();
    Field[] fields = clazz.getFields();
    for (Field field : fields) {
        if (!field.get(a).equals(field.get(b))) {
            return false;
        }
    }
    return true;
}

The logic is pretty self-explanatory. Here is the usage:

Student s1 = new Student("Tom", 1);
Student s2 = new Student("Tom", 1);
try {
    System.out.println(allFieldsEqual(s1, s2));
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

Student is defined as:

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313