Comparing 2 HashMap with Key as String and Value as UserDefined Object

Viewed 36

I want to output a boolean as true indicating both maps have same Key and values. If i use equals() it returns false. How can i output as true , Object references are different. But the entries are same I have 2 maps below

Map<String,Information> map1=new HashMap<>();
map1.put("key1", new Information("10","20","30","40"));
map1.put("key2", new Information("11","22","33","44"));
Map<String,Information> map2=new HashMap<>();
map2.put("key1", new Information("10","20","30","40"));
map2.put("key2", new Information("11","22","33","44"));

POJO as below : with public getters and setters

public class Information {

private String value1;
    private String value2;
    private String value3;
    private String value4;

public Information(String value1,
                      String value2,
                      String value3,
                      String value4)
{
   this.value1 = value1;
   this.value2 = value2;
   this.value3 = value3;
   this.value4 = value4;
}
}
2 Answers

A HashMap uses equals() to compare two entries. For HashMap<String, Information>, it uses equals() of String and Information to decide if two entries are equal. Since your Information class does not override equals() from Object, the equality comparison is based on addresses.

To compare two Information by value, you can override equals() inside Information class:

@Override
public boolean equals(Object obj) {
    if (obj == null) return false;
    if (obj == this) return true;
    if (obj instanceof Information info) {
        return value1.equals(info.value1) &&
               value2.equals(info.value2) &&
               value3.equals(info.value3) &&
               value4.equals(info.value4);
    }
    return false;
}

You have to feed the same objects like this

    Information info1 = new Information("10", "20", "30", "40");
    Information info2 = new Information("11", "22", "33", "44");
    Map<String, Information> map1 = new HashMap<>();
    map1.put("key1", info1);
    map1.put("key2", info2);
    Map<String, Information> map2 = new HashMap<>();
    map2.put("key1", info1);
    map2.put("key2", info2);

    System.out.println(map2.equals(map1));// prints true

You are getting false cause you are comparing two different instances of Information classs.

Related