Correct way to override equals method in Java
by , 11-08-2011 at 04:01 PM (693 Views)
Though it is very simple to override "equals" method for a class. But people usually make mistakes in overriding this method. It is very important for a Java developer to know about this method.
Some Important points to remember
Always remember to override "hashCode" method if you are overriding "equals" method otherwise you may face problem while using your class with HashTable, HashMap like classes as they uses "hashCode" internally.
If two objects are equal then their "hashCode" must be same but converse is not true means unequal objects can have the same hashCode.
Here is the correct way to override equals method.
OutputJava Code:public class Test { private int num;private String data; public Test(int num, String data) { this.num = num; this.data = data; } public boolean equals(Object obj) { if (this == obj) return true; if ((obj == null) || (obj.getClass() != this.getClass())) return false; Test test = (Test) obj; return num == test.num && (data == test.data || (data != null && data .equals(test.data))); } public int hashCode() { return num + (null == data ? 0 : data.hashCode()); } public static void main(String[] args) { Test test = new Test(2, "4"); Test test2 = new Test(2, "4"); System.out.println(test.equals(test2)); } } } public boolean equals(Object obj) { if (this == obj) return true; if ((obj == null) || (obj.getClass() != this.getClass())) return false; Test test = (Test) obj; return num == test.num && (data == test.data || (data != null && data .equals(test.data))); } public int hashCode() { return num + (null == data ? 0 : data.hashCode()); } public static void main(String[] args) { Test test = new Test(2, "4"); Test test2 = new Test(2, "4"); System.out.println(test.equals(test2)); } } }
true









Email Blog Entry
sorry for all the questions
thanks...
06-14-2013, 02:22 PM in gbonecapone