|
Re: equals doubt
|
Posted: Apr 26, 2002 2:11 PM
|
|
Sorry.Your conclusion is not correct. Let me explain you about equals() method in brief. When you write v1.equals ( v2 ) , then equals compares the references of v1 and v2. Since v1 and v2 are two different objects equals() returns false. By default, equals for any objects doesn't do any comparision on their data members. In your case v1.equals ( v2 ) doesn't do anything on v1.i and v2.i . It just compares the references (pointer) of v1 and v2. However, you can override equals () method for your class and then you can compare any data members for your class inside your equals() method. For example, String class overrides equals() method and compares the content stored in the String object. For your class Value you can override equals method as:
public class Value {
int i ;
public boolean equals ( Object aValue ) {
if ( this == aValue ) {
return true;
}
if ( aValue instanceOf Value ){
Value v = (Value) aValue;
if ( i == v.i ) {
return true;
}
}
return false ;
}
}
Now , if you say v1.equals ( v2 ) then it will return true in your case , because in equals() method in Value class compares i data member value.
The == operator always compares the reference of two objects. In case of primitive data type it compares the values. Therefore, equals() can compare (and by default it does compare references) content as well as references of two objects. To compare the contents of two objects you must override equals method in that class.
Thanks Kishori
|
|