What is the difference between overriden equals and equals? [duplicate] - java

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 3 years ago.
I am new to Java and StackOverflow but as i have read some of the answers about equals they stated :
Equals method compares two objects for their identity and if they are
identical it returns TRUE . whereas if you don't override the method Equals
it acts like ==(which returns true if 2 variables refer to the same object).
Integer x = new Integer(4);
Integer y = new Integer(4);
System.out.println(x.equals(y));
System.out.println(x == y);
If the queries above are correct why does this code print TRUE and FALSE since we are not overriding the method equals?

Because class Integer does override the equals method and it's implementation is the following:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

Related

Overwritten equals() method requires null check? (java) [duplicate]

This question already has answers here:
Is null check needed before calling instanceof?
(8 answers)
Closed 4 years ago.
I have written a simple equals() method for a class:
#Override
public boolean equals(Object obj) {
if(obj instanceof Cl) {
Cl u = (Cl)obj;
return u.i == i;
} else {
return false;
}
}
As I know, if I want compare if the class object equals to a null object, this returns false because of the instanceof, but according to my uni teacher this is a bad implementation, as the null check is missing. Can someone confirm for me if my theory is correct or not?
I think, a null check is not required and should not be there, because in this case there will not be any compile-time error or any exception if obj is null, because of the check if (obj instaceof C1).

What does the this == obj syntax mean? [duplicate]

This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
What is the difference between == and equals() in Java?
(26 answers)
Closed 4 years ago.
the following is the equals method from the String class:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value,aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
What does the comparison: 'this == anObject' at the first if statement mean?
It compares the memory addresses for both the object passed as parameter and the one you call equals from. If they are in the same memory address, they are obviously the same object.
Otherwise, it keeps checking for other ways to compare if they are actually equivalent objects.

Check if object is of type String [duplicate]

This question already has answers here:
How to determine an object's class?
(13 answers)
Closed 6 years ago.
I need to write a new method that checks if certain values are of the type String or not.
I have two objects and I want to be able to check if these two objects are strings, if they are to then return true, and false otherwise.
I did start off with the following method:
public boolean stringTest()
{
boolean aString;
}
But could not get anything to work after that, any help would be greatly appreciated!
You can make use of instanceof and rewrite your method
public boolean stringTest(Object any)
{
return any instanceof String;
}
then
stringTest(townName); // true
stringTest(new Integer()); // false
Use instanceof:
public boolean isString(Object o) {
return o instanceof String;
}

Why are two objects with same data not equal while using equals() method [duplicate]

This question already has answers here:
Why do I need to override the equals and hashCode methods in Java?
(31 answers)
Closed 9 years ago.
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.
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()
You need to overrides equals
#Override
public boolean equals(Object obj) {
if (!(obj instanceof Account))
return false;
Account that = (Account) obj;
return (account == null ? that.account == null : account
.equals(that.account)) && balance == that.balance;
}
I almost forgot to override hashCode when overriding equals
#Override
public int hashCode() {
int hash = 17;
hash = 37 * hash + (account == null ? 0 : account.hashCode());
long l = Double.doubleToLongBits(balance);
hash = 37 * hash + (int) (l ^ (l >>> 32));
return hash;
}
You did not override equals. The default equals implementation, inherited from Object, returns true if and only if the two variables point to the same object.
Override equals to check for field equality (and hashCode, if you're at it).
The Object.equals() method is testing to see if the two things being compared are LITERALLY the same object. While a1 and a2 contain the same information, they are different objects in memory.
If you want to test equality of the information inside your objects you can have the class implement the Comparable interface and override the compareTo method.
Since you don't override .equals() (and if you do, you must also override .hashCode()), you use Object's .equals() implementation; and this implementation returns true if and only if the object references are equal (ie, o1 == o2).
You need to override Object.equals() method.
It would show true if a1.balance==a2.balance . Note that the equals() compares objects and not their actual values. To be able to compare an Object you have to overwrite the equals() method.
See here for more info Comparing two objects using an equals method, Java
The implementation in Object class i.e. the default implementation checks the references.
So if the references are same it returns true else it returns false.

How does equals() method work in Java [duplicate]

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 9 years ago.
The equals method compares whether two object values are equal or not. My question is how it compares the two objects? How can it tell the two objects are equal or not? I want to know based on what it compares the two objects. I am not including the hashCode method.
The default implementation, the one of the class java.lang.Object, simply tests the references are to the same object :
150 public boolean equals(Object obj) {
151 return (this == obj);
152 }
The reference equality operator is described like this in the Java Specification :
At run time, the result of == is true if the operand values are both
null or both refer to the same object or array; otherwise, the result
is false.
This default behavior isn't usually semantically satisfying. For example you can't test equality of big Integer instances using == :
Integer a = new Integer(1000);
Integer b = new Integer(1000);
System.out.println(a==b); // prints false
That's why the method is overridden :
722 public boolean equals(Object obj) {
723 if (obj instanceof Integer) {
724 return value == ((Integer)obj).intValue();
725 }
726 return false;
727 }
which enables this :
System.out.println(a.equals(b)); // prints true
Classes overriding the default behavior should test for semantic equality, based on the equality of identifying fields (usually all of them).
As you seem to know, you should override the hashCode method accordingly.
Consider following example,
public class Employee {
String name;
String passportNumber;
String socialSecurityNumber;
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee();
boolean isEqual = e1.equals(e2); // 1
System.out.println(isEqual);
}
}
In the code at comment //1 it calls inherited equals method from Object class which is simply comparing references of e1 and e2. So it will always give false for each object created by using new keyword.
Following is the method excerpt from Object
public boolean equals(Object obj) {
return (this == obj);
}
For comparing equality check JLS has given equals method to override in our class. It is not final method. JLS doesn't know on what basis programmar wants to make two objects equal. So they gave non-final method to override.
hashcode does not play role to check object's equality. hashcode checks/finds the Bucket where object is available. we use hashcode in hashing technique which is used by some classes like HashMap..
If two object's hashcode are equals that doesn't means two objects are equal.
For two objects, if equals method returns true then hashcode must be same.
You will have to override equals method to decide on which basis you want object e1 and e2 in above code is equal. Is it on the basis of passportNumber or socialSecurityNumber or the combination of passportNumber+socialSecurityNumber?
I want to know based on what it compares the two objects.
Answer is, by default with the help of inherited Object class's equals method it compares two object's reference equality by using == symbol. Code is given above.
logically, equals does not compare objects (however you can do anything with it), it compares values. for object comparison there is '==' operator

Categories

Resources