Gaetano de Gennaro
Gaetano de Gennaro

Reputation: 101

How to compare two HashMap in Java

I need to compare two HashMap using Java. I tried with equals() method, but that isn't working. I think, maybe, that's why in HashMap equals() method uses object references to compare, and not object values. Example:

/*FIRST HASHMAP*/
Posto p1 = new Posto("005","Cat1");
Posto p2 = new Posto("001", "Cat2");
Posto p3 = new Posto("009", "Cat2");
Posto p4 = new Posto("005","Cat3");

Map<String, Posto> posti = new HashMap<String, Posto>();

posti.put(p1.getCode(), p1);
posti.put(p2.getCode(), p2);
posti.put(p3.getCode(), p3);
posti.put(p4.getCode(), p4);

/*SECOND HASHMAP*/  
Posto p5 = new Posto("005","Cat1");
Posto p6 = new Posto("001", "Cat2");
Posto p7 = new Posto("009", "Cat2");
Posto p8 = new Posto("005","Cat3");

Map<String, Posto> pos = new HashMap<String, Posto>();

pos.put(p1.getCode(), p5);
pos.put(p2.getCode(), p6);
pos.put(p3.getCode(), p7);
pos.put(p4.getCode(), p8);

/*COMPARE*/
System.out.println(posti.equals(pos)); //THIS RETURNS FALSE (SHOULD BE TRUE)

Upvotes: 2

Views: 154

Answers (1)

Sebastian Brudzinski
Sebastian Brudzinski

Reputation: 878

Actually, you are not right by saying the equals method of the HashMap compares by references and not values. The equals method is inherited from the AbstractMap, which defines the equals method as following:

This implementation first checks if the specified object is this map; if so it returns true. Then, it checks if the specified object is a map whose size is identical to the size of this map; if not, it returns false. If so, it iterates over this map's entrySet collection, and checks that the specified map contains each mapping that this map contains. If the specified map fails to contain such a mapping, false is returned. If the iteration completes, true is returned.

Source: https://docs.oracle.com/javase/7/docs/api/java/util/AbstractMap.html#equals(java.lang.Object)

As the comments suggest, make sure that the hashCode and equals methods of your class are correct.

Upvotes: 5

Related Questions