Thursday, October 28, 2010

One reason for equals and compareTo methods to have same symantic

Suppose you have Class which is comparable, then symantics of equal and comapreTo methods should same.
i.e If o1.equals(o2) is true , then o1. comareTo(o2) should be 0 and vice verse.

What happens when above condition is not maintained, I wrote below peace code to test that.
public class Main1 {
public static void main(String[] args) {

MyData[] darray = {new MyData(1, "siva"), new MyData(2, "siva"), new MyData(3, "siva3"), new MyData(4, "siva4")};
System.out.println(darray[0].equals(darray[1]));
System.out.println(darray[0].compareTo((darray[1])));
TreeSet set = new TreeSet();
System.out.println("**********TreeSet*****************");
System.out.println(set.add(darray[0]));
System.out.println(set.add(darray[1]));

TreeMap map = new TreeMap();
System.out.println("**********TreeMap*****************");
System.out.println(map.put(darray[0], "1"));
System.out.println(map.put(darray[1], "2"));

HashMap map2 = new HashMap();
System.out.println("**********HashMap*****************");
System.out.println(map2.put(darray[0], "1"));
System.out.println(map2.put(darray[1], "2"));

HashSet set2 = new HashSet();
System.out.println("**********HashSet*****************");
System.out.println(set2.add(darray[0]));
System.out.println(set2.add(darray[1]));
}
}

public class MyData implements Comparable {
public MyData(int value, String name) {
super();
this.value = value;
this.name = name;
}
private int value;
private String name;
@Override
public int compareTo(MyData o) {
//Comparison based on name
return name.compareTo(o.name);
}
public int getValue() {
return value;
}
public String getName() {
return name;
}

@Override
public boolean equals(Object o){
if(o instanceof MyData){
//Equals behavior is based on int value
return this.value == ((MyData)o).value;
}
return false;
}
}

//------output is----------//
false
0
**********TreeSet*****************
Added
Already Exist
**********TreeMap*****************
Added
Already Exist
**********HashMap*****************
Added
Added
**********HashSet*****************
Added
Added
-------------------------------------------------------------------
There is a difference behavior of different Set and Map based on their implementation.
Is there a way to enforce compareTo and equals have same behavior ? Well its upto the java programmer to guarantee this semantics.

Define equals when ever compareTo is defined.