I learned that == checks if the references being compared are the same,, while .equals() compares the two states. So then why can we use == inside the .equals() method?
Like for example:
public boolean equals(Object o){
//cast o to SimpleBankAccount
SimpleBankAccount b = (SimpleBankAccount)o;
//check if all attributes are the same
if ((this.balance == b.balance) && (this.accountNumber == b.accountNumber)){
return true;
}
else{
return false;
}
}
Why would the this.balance and b.balance have the same reference?
-
3That statement isn't necessarily true. That only works if the balance member is a primitive data type.Supericy– Supericy2013年03月04日 18:31:32 +00:00Commented Mar 4, 2013 at 18:31
7 Answers 7
The equals method is to compare objects. When using the "==" to test for equality, the only time it will function as expected is when it is comparing primitive or native types, or you are actually testing to see if two pointers refer to the same object. That is, balance is more than likely of type int, float or double, which means "==" will test for equality as expected. If balance was of type Balance, then this would not work.
1 Comment
"as expected" is relative. If I use == on objects it will do exactly what I expect it to do (compare the references, which is what you want sometimes).References are also similar to primitive types along with int, chars and doubles in that when you do == you're literally comparing the binary representation of those types.
Comments
because balance is likely a primitive, correct? like an int or a float? so you are comparing the value of balance. With objects you are comparing the references, but with primitives you are comparing the actual data value
Comments
Depends on what balance is.
If balance is a primitive, then == will compare the values, which is correct.
Comments
== is normally used inside the equals method to check if the two references are actually the same object. If they are not, further checking goes to see if objects have the same state.
Comments
If you want to compare the value of balance/accountNumber and they are primitives or primitive Wrappers (like Integer) then == is how you compare the value. The wrappers will be autoboxed.
1 Comment
System.out.println(new Integer(1) == new Integer(1)); prints false (because it compares the references).If this equals method works, then it's because the balance and accountNumber variables are primitive types such as int or double, and == does compare the values for primitive types.
2 Comments
"works" lies in what you expect it to do. It can work if you want to see if they are actually references to the exact same object. Note unboxing won't be automatically - "System.out.println(new Integer(1) == new Integer(1));" prints false.