0

How to check two different classes having the same attributes in different order have the same values

public class Person {
        String name;
        Long age;
        // getters and setters
        // equals and hashcode    
}

Second class attributes in different order

public class PersonTwo {            
            Long age;
            String name;

            // getters and setters
            // equals and hashcode    
    }

Checking two objects equal

        Person person = new Person();
        person.setAge(122L);
        person.setName("Paul");

        PersonTwo person2 = new PersonTwo();
        person2.setName("Paul");
        person2.setAge(122L);
        
        boolean result = Objects.equals(person2, person);

This will return false, cannot make changes in both classes as they are from another library.

Instead of comparing each attribute value, any easy ways to do this?

Cork Kochi
  • 1,783
  • 6
  • 29
  • 45
  • 2
    You could use reflection since the getters have the same name in both classes, but for 2 fields? Just compare the fields manually: `boolean result = Objects.equals(person2.getAge(), person.getAge()) && Objects.equals(person2.getName(), person.getName());` – f1sh Jan 05 '22 at 10:34
  • @fish classes have more fields, just shown an example, can you show the example using reflection? – Cork Kochi Jan 05 '22 at 10:35
  • You can look here https://stackoverflow.com/questions/3333974/how-to-loop-over-a-class-attributes-in-java – sagi Jan 05 '22 at 10:38
  • Is it really due to the order of fields? - because I don't see a way to do this, if not deliberately. Or does `PersonTwo.equals` include a line like `if (obj instanceof PersonTwo`)? – Izruo Jan 05 '22 at 10:39

1 Answers1

1

The order of the attributes has no bearing on the equality of these objects. They are distinct classes so Objects.equals(Object,Object) will return false regardless of the fields of those classes because it uses the equals method of the first argument to determine equality after performing null comparisons. Since both classes are part of external libraries you cannot hack a change to the equals method of either (which is just as well because that is a bad idea).

You could create your own version of Objects.equals(..) to handle this specific case. A better approach would be to convert one of the instances into the other type and then you can compare them. However, this assumes that equals is properly implemented for either (something that is out of your control since they come from external libraries). You could also convert both of them to your own class (MyPerson?), implement a proper equals, and then you know it will behave as intended.

vsfDawg
  • 1,425
  • 1
  • 9
  • 12