Unexpected results for TreeMap with inconsistent compareTO and equals.

If two objects are considered equal by compareTo() and not by equals() or vice-versa, then TreeSet and TreeMap may produce different output.

public class Employee implements Comparable <<>>
{
int empNo;
String empName;

@Override
public int hashCode() { return empNo; }

@Override
public boolean equals(Object obj)
{
Employee other = (Employee) obj;
if (empNo == other.empNo && empName.equals(other.empName))
return true;
return false;
}

@Override
public int compareTo(Employee other)
{
return (empNo – other.empNo);
}

@Override
public String toString() { return “[” + empNo + “, ” + empName + “]”; }

public Employee(int empNo, String empName)
{
this.empNo = empNo;
this.empName = empName;
}

public static void main(String[] args)
{
Employee employees[] = new Employee[5];
employees[0] = new Employee(1, “Grima”);
employees[1] = new Employee(2, “Krishma”);
employees[2] = new Employee(2, “Krishma”);
employees[3] = new Employee(4, “Krishma”);
employees[4] = new Employee(2, “Gurav”);

HashSet set = new HashSet();
set.addAll(Arrays.asList(employees));
System.out.println(set.toString());

TreeSet treeSet = new TreeSet();
treeSet.addAll(Arrays.asList(employees));
System.out.println(treeSet.toString());
}
}

[[1, Grima], [2, Krishma], [2, Gurav], [4, Krishma]] // HashSet
[[1, Grima], [2, Krishma], [4, Krishma]] //TreeSet

Now as per the “equals” method in Employee two employee objects will be equal if their empNo and empName are equal while “compareTo” method says that two employee objects will be equal if two employee objects have same empNo.

So the output of the hashset is expected, employees with different empNo. and empName are added to set, but if we look at output of TreeSet, employees only with different empNo are added.

Thus we can conclude that TreeMap does not use hashCode() or equals() and it uses the compareTo() method.
This could result in a serious application error where two objects considered equal by equals() return different values from TreeMap.

Summary: All 3 methods – compareTo, equals and hashCode should be consistent with each other.

Advertisements