-3

Hey i have two java class object, whose key and values are same but when I check ob1.equals(obj2) its return false.

here is the code :

   Category expected = new Category("01","lorem","custom");


  ResponseEntity<List<LinkedHashMap>> response = restTemplate.exchange("/api/categories", HttpMethod.GET,
                        null, new ParameterizedTypeReference<List<LinkedHashMap>>() {});

LinkedHashMap result = response.getBody().get(0); // which is same as expected object

//check if equals

 private boolean areEqual(LinkedHashMap result, Category expected) {
        String catId = (String) obj.get("category_id"); //is 01
        String name = (String) obj.get("category_name"); // is lorem
        String sec = (String) obj.get("section_name");   // is custom
        DefaultCategory temp = new Category(catId, name, sec);
        return temp.equals(expected);  //<--------- returning false, even they are equal
    }

The api return this category

 @GetMapping("categories")
    public ResponseEntity<List<Category>> getDefaultCategories() {
        List<Category> categories = new ArrayList();
        categories.add(new Category("01","lorem","custom"));
        return new ResponseEntity<>(categories, HttpStatus.OK);
    }
user8462556
  • 369
  • 6
  • 13

2 Answers2

2

Standard .equals(...) checks two objects are same instance or not. If you want to compare two objects with their fields. You can override equals method like below.

public class DefaultCategory {
    private String catId;
    private String name;
    private String sec;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof DefaultCategory)) return false;

        DefaultCategory other = (DefaultCategory) o;
        if(!Objects.equals(other.catId, catId)) return false;
        if(!Objects.equals(other.name, name)) return false;
        if(!Objects.equals(other.sec, sec)) return false;

        return true;
    }
}
Ismail Durmaz
  • 2,521
  • 1
  • 6
  • 19
-1

Because expected is a child class and temp is a super class or vice versa. You are comparing two different objects(types). Cast you temp to Category and you will be fine. Or override your equals to allow mixed type comparison.

ringadingding
  • 475
  • 5
  • 14
  • hi @ringadingding, you are right. The author wants to compare each instance with their fields. We can compare objects without their class hierarchies. Also, many practices check object classes but we don't have to. I think the author does not override `equals` method to validate each field values, so I overrode `equals` of the super class. – Ismail Durmaz Jan 15 '21 at 10:07