Showing posts with label HashMap. Show all posts
Showing posts with label HashMap. Show all posts

How to Override Object.equals() method in Java . Writing own equals() method to compare two objects based on values with example code

This tutorial covers how to write own version of equals() method and importance of the method. Before going to this , let us see litle bit about Object class which has equals() and hashcode() method. Object class is the superclass of all Java classes. Every classes in java are inherited from this class by default that means all methods of the Object class are inherited automatically. So by default , the classes that we create will have the methods equals() , hashcode() , toString(), etc ...
This tutorial covers the default implementation of equals method and when and why we need to override equals method for our class?
In default implementation , two objects are equal only if they refer to the exact same object (i.e. reference / memory address equality) . The following code represents the default equals method
public boolean equals(Object obj) { return (this == obj); }

When to override Object.equals() method? Please go through the following code and the output.
    
class equalTest
{
public static void main(String arg[])
{
Employee emp1=new Employee(1561, "John", "Smith");
Employee emp2=new Employee(1561, "John" ,"Smith");
Employee emp3=emp1;
if (emp1.equals(emp2)) System.out.println("Both Employees(emp1 , emp2) are equal");
else System.out.println("Both Employees(emp1 , emp2) are not equal");

if (emp3.equals(emp1)) System.out.println("Both Employees(emp1 , emp3) are equal");
else System.out.println("Both Employees(emp1 , emp3) are not equal");

String name1="John Smith";
String name2="John Smith";

if (name1.equals(name2)) System.out.println("Both Names(name1 , name2) are equal");
else System.out.println("Both Names(name1 , name2) are not equal");

}
}

class Employee
{
int empCode;
private String firstName;
private String surname;

public Employee(int empCode, String firstName, String surname)
{
this.empCode=empCode;
this.firstName=firstName;
this.surname=surname;
}
}

Output :
D:\as2\JF4>java equalTest
Both Employees(emp1 , emp2) are not equal
Both Employees(emp1 , emp3) are equal
Both Names(name1 , name2) are equal

Before overriding , it is very important to keep in mind the distinction between equality and identity . In the above code , emp1 and emp2 has identical data i.e. employee code , first name and surname are equal for both objects . But the output is Both Employees(emp1 , emp2) are not equal . Because, by default the equals method of object checks whether the two reference variables(emp1 and emp2 ) refer to the same object . In the above code , both are different objects that is not identical . But emp1 and emp3 are identical . So the output is Both Employees(emp1 , emp3) are equal .
emp1 and emp2 objects are logically equal but not identical . In this situation , we have to override equals method sothat the it can also check the logical equality . But name1 and name2 are two different string objects . But the output is Both Names(name1 , name2) are equal . Because String class overrides the equals method to compare two string objects for equality based on the values and returns true if they hold the same characters in the same sequence.
Date class defines the equals method as follows . This is the value-based approach to equality (logical equality) . Both Date objects are equal if the getTime() method returns the same long value (milliseconds) for both
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}

So when is it appropriate to override Object.equals? When a class requires logical equality ( i.e. two objects are equal if they have identical data)) that differs from object identity, and a superclass has not already overridden equals method to implement the desired behavior . This is generally applicable for value classes such as String , Integer and Date, etc . When we compare two objects using the equals method , we may expect to find out whether they are logically equivalent, not whether they refer to the same object. In this situation , we need to override equals method.
typesafe enum value class that does not require the equals method to be overridden . Because typesafe enum classes guarantee that at most one object exists with each value, Object’s equals method is equivalent to a logical equals method for such classes. When you override the equals method of java.lang.Object , you must adhere to its general contract which is given below
Let us say a, b and c are references of any objects . The equals method is
1. reflexive: a.equals(a) must return true i.e. any object must be equal to itself
2. symmetric: a.equals(b) must be true if b.equals(a) is true. i.e. if first object is equal to a second and the second object is equal to first
3. transitive: if a.equals(b) returns true and b.equals(c) returns true, then a.equals(c) must return true . i.e. if first object is equal to a second and the second object is equal to a third, then the first object must be equal to the third.
4. consistent: multiple invocations of a.equals(b) should return the same result (i.e. either always true or always false) unless any of the object's information is modified
5. Non-nullity : x.equals(null) must return false where x is non-null reference. i.e. all objects must be unequal to null. Allowing null value should not throw NullPointerException .
Note : It is better to check null i.e. if (o == null) return false;. But ,this test is not necessary as we include another test instanceof operator to check that its argument is of the correct type i.e. if (!(o instanceof MyType)) return false; This take takes care of the null check also . instanceof operator is specified to return false if its first operand is null . null objects will always fail instanceof.
equals() method will have the following condtions and statements in the following order and applicable for the above class Employee
public boolean equals(Object other) {
1. check other object refers the same object . use == operator . If so, return true
- if (other==this ) return true
2. check that its argument is of the correct type before type casting
- if (!(other instanceof Employee)) return false // takes care of null check also .
3. type cast the argument to an appropriate type to access its fields
- Employee emp = (Employee) other
4. check to see if the fields (relevent to logical equality) of the argument matches the corresponding fields of this object . If all checks succeed, return true. For primitive fields (except float or double) , use the == operator for comparisons; for object reference fields, invoke the equals method recursively .To avoid NullPointerException, when the fields contain null values , please include null check as given below.
- return empCode == emp.empCode && (firstName == emp.firstName || (firstName != null && firstName.equals(emp.firstName) ))&& (surname == emp.surname || (surname != null && surname.equals (emp.surname)))

}
Note : instanceof is most suitable for immutable class or final class which can not be extended . As instanceof returns true for subclass also , we can use getCalss() method for type check as given below
if((other == null) || (other.getClass() != this.getClass())) return false . null check also required.

Aoid common mistakes when overriding
1. You must override hashCode in every class that overrides equals. If not , it will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable. For overriding hashCode() method , please gothrough my earlier tutorial Why and When to override Object.hashCode() method?
2. Don’t use any other type other than Object as argument in the equals method declaration .
Wrong : public boolean equals(Employee o) {... } - this method does not override Object.equals() , but overloads it instead. Object.equals accepts only the argument of type Object ,
Correct : public boolean equals(Object o) {... }

The above Employee class with equals() and hashCode() method is given below. The equals() method of Object class is overrided in the code to compare objects based on values.
    
class equalOverride
{
public static void main(String arg[])
{
Employee emp1=new Employee(1561, "John", "Smith");
Employee emp2=new Employee(1561, "John" ,"Smith");
Employee emp3=emp1;
if (emp1.equals(emp2)) System.out.println("Both Employees(emp1 , emp2) are equal");
else System.out.println("Both Employees(emp1 , emp2) are not equal");
if (emp3.equals(emp1)) System.out.println("Both Employees(emp1 , emp3) are equal");
else System.out.println("Both Employees(emp1 , emp3) are not equal");
String name1="John Paul";
String name2="John Paul";
if (name1.equals(name2)) System.out.println("Both Names(name1 , name2) are equal");
else System.out.println("Both Names(name1 , name2) are not equal");
}
}

class Employee
{
int empCode;
private String firstName;
private String surname;

public Employee(int empCode, String firstName, String surname)
{
this.empCode=empCode;
this.firstName=firstName;
this.surname=surname;
}
public boolean equals(Object other) {
if (other==this ) return true;
if (!(other instanceof Employee)) return false;
Employee emp = (Employee) other;
return empCode == emp.empCode && (firstName == emp.firstName || (firstName != null && firstName.equals(emp.firstName) ))&& (surname == emp.surname || (surname != null && surname.equals (emp.surname))) ;
}

public int hashCode() {
int hash = 17;
hash = hash * 19 + empCode;
hash = hash * 31 + firstName.hashCode();
hash = hash * 13 + (surname == null ? 0 : surname.hashCode());
return hash;
}
}



Output:

Read more...

How to Sort HashMap by Values . Write Own Compare Method in Java Example

We can sort the Hashmap by putting all values in a TreeMap . By default TreeMap is sorted by Keys. To sort it by values , we have to write own compare method of comparator interface. The compare method compares its two arguments . By default two arguments are objects which is having key of Map. If both arguments are equal then it returns 0 . If first argument is less than the second argument , returns a negative integer, If first argument is greater than the second argument , returns a Positive integer. Now we have to sort by values. So we have to get the values using key i.e map.get(key) . Now we have to write our own logic to compare the values . The return value will be 0 or 1 or -1 . If more than one elements are equal it adds only the first value. If both arguments are equal means it returns 0 that means Hashmap is having duplicate values. As HashMap does not allow duplicate values ,to allow duplicate values , we have to return other than 0 value. In our example , when both values are equal , we compare both keys rather than values , thus returns other than 0. The following program is compatible for sorting of strings and also positive numbers. Negative numbers are sorted properly because we are using String.compareTo to compare two values. So it is always better to pass same type of values and change the compareTo logic accordingly. For example if all the values are integer means , the logic will be Integer e1 = (Integer)thisMapValues.get(o1); Integer e2 = (Integer) thisMapValues.get(o2); if (e1==e2) return return String.valueOf(o1).compareTo(String.valueOf(o2)) ; else if (e1<e2) return -1 ; else return 1;

import java.util.*;
public class HashMapSortValue{
private static class OwnCompare implements Comparator
{
private Map thisMapValues = null;
public OwnCompare (Map mapValues)
{
super();
thisMapValues = mapValues;
}

public int compare(Object o1, Object o2)
{
String e1 = String.valueOf(thisMapValues.get(o1));
String e2 = String.valueOf( thisMapValues.get(o2));
if (e1.compareTo(e2)==0) return String.valueOf(o1).compareTo(String.valueOf(o2)); else return e1.compareTo(e2);

}
}

public static void main(String[] args) {
Map hm = new HashMap();
hm.put ("Employee1", 60000);
hm.put ("Employee2", 50000);
hm.put ("Employee2", "absent");
hm.put ("Employee3", 25000);
hm.put ("Employee4","retired");
hm.put ("Employee5","absent");
hm.put ("Employee6",20000);
hm.put ("Employee7",20000);
hm.put ("Employee8",50000);
hm.put ("Employee9",60000);
System.out.println("List Before Sorting : " + hm);
SortedMap sortedByValue = new TreeMap(new HashMapSortValue.OwnCompare(hm));
sortedByValue.putAll(hm);
System.out.println("List After Sorting by Value " +sortedByValue);
}
}


Output :

Read more...

 
Copyright 2011 Java Online