In Object class equals method is present. Its default behavior is to do '==' comparision, i.e., to see if the same Object is being referred by two references.
Below is the definition of equals() in Object class
public boolean equals(Object paramObject){
return (this == paramObject);
}
Let's guess the output of following snippet :
String str = "test";
String str2 = "test";
boolean flag =str.equals(str2);
System.out.println("String EQUAL :"+flag);
Guessed it right...It returns true. But How Come ?
In String class, equals method is overridden. Below snippet is its sample definition in String Class
public boolean equals(Object paramObject){
if (this == paramObject) {
return true;
}
if (paramObject instanceof String) {
//code to check whether the value of the current object is same as paramObject or not
return true;
}
return false;
}
It returns true if
1) Two references of type String refers to Same object on heap or
2) Value of two String objects are equal, provided two String objects are created
without new operator
Supoose, we have a custom class 'Name' as below :
class Name{
private String firstName;
Name(String firstName){
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
Let's guess the output of following snippet :
Name name1 = new Name("test");
Name name2 = new Name("test");
boolean flag = name1.equals(name2);
System.out.println("Name EQUAL :"+flag);
Its false. On instantiation, jvm searches for equals() in Name Class, as it doesn't find, it searches it in its super class Object. Behavior of equals method's behavior in Object class is to do '==' comparision. As name1 and name2 refer to 2 different objects, it returns false.
Lets include the beolw sinppet in Name class :
@Override
public boolean equals(Object obj) {
Name name = (Name)obj;
return this.firstName.equals(name.getFirstName());
}
Now,equals() in Name class is called.Instance variable value of object name1 is checked against instance variable value of object name2. Instance variable determines the state of the Object. Hence it returns true.
To make 2 different instances equal based on its state, we need to override equals method.
Source Code can be downloaded @ TestEquals
If you are able to express something you learnt in a simple manner, then you can be confident that you knew it well enough. This blog is an attempt by a learner to prove the above fact.
Sunday, April 4, 2010
Subscribe to:
Posts (Atom)
About Me
- Bhanu Prakash
- Hyderabad, Telangana , India
- I may NOT be what my MIND thinks. I believe I am what my HEART feels. I am a drop in an ocean if ocean is the divinity. The moment drop merges into ocean, it loses its identity. So am I. Until then I am what I am, eagerly awaiting for the merger.