public class Account {
String account;
double balance;
Account(String account, double balance) {
this.account = account;
this.balance = balance;
}
}
public class AccountTest {
public static void main(String[] args) {
Account a1 = new Account("Sandy", 1000);
Account a2 = new Account("Sandy", 1000);
System.out.println(a1.equals(a2));
}
}
When i execute it showing "false" but objects contains same data in variables.why?explain.
Objects are not compared by value: two objects are not equal even if they have the same properties and values. This is true of arrays too: even if they have the same values in the same order. Objects are sometimes called reference types to distinguish them from JavaScript's primitive types.
equals() method in Java. Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
The equals() method is a static method of the Objects class that accepts two objects and checks if the objects are equal. If both the objects point to null , then equals() returns true .
Because by default object checks equality based on equals(Object obj).
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
If you want to check equality with equals()
method in your class equal you have to override equals() method of Object
class.
how-to-override-equals-method-in-java, Like following:
@Override
public boolean equals(Object obj) {
// your implementation
}
And you should always override hashCode() whenever overriding equals method of Object
class.
#Effective Java, by Joshua Bloch
You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.
You need to override equals() method, and use it whenever you want to compare their values.
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Account other = (Account) obj;
if ((this.account== null) ? (other.account!= null) : !this.account.equals(other.account)) {
return false;
}
if (this.balance!= other.balance) {
return false;
}
return true;
}
BUT WHY I HAVE TO OVVERIDE EQUALS()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With