View RSS Feed

My Java Tips

Correct way to override equals method in Java

Rate this Entry
by , 11-08-2011 at 05:01 PM (1073 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.





Java 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));

}

}

}
Output

true

Submit "Correct way to override equals  method in Java" to Facebook Submit "Correct way to override equals  method in Java" to Digg Submit "Correct way to override equals  method in Java" to del.icio.us Submit "Correct way to override equals  method in Java" to StumbleUpon Submit "Correct way to override equals  method in Java" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments