+3

Equals()

I can't understand the equals() method in java. Help me.

3/16/2019 6:38:16 AM

Jonny Walker

7 Answers

New Answer

+14

The equals method is defined in the Object class, the mother of all classes which every class implicitly extends. The implementation in the object class is quite simple and often not what you want. It returns true if you call the method from an object and pass in the identical object as an argument. The same what == comparison would result. This is why the equals method often needs to be overridden to compare the classes field values instead of just the object reference. String overrides equals() to deeply compare two Strings, meaning the content of the underlying char array. Note that you must override hashCode if you override equals. More on the topic: https://www.baeldung.com/java-equals-hashcode-contracts

+7

The equals method compares the value of two variables, and returns true if they are equal, and false if they’re not.

+6

This might help to visualise the diffrenece. String x = "hello"; String y = new String("hello"); //i have to create a new string object of hello here beacuse if i didnt x and y would both be pointing to the same "hello" in string pool meaning that there refrences would be the same if compared. System.out.println("Are both values the same? "+x.equals(y)); System.out.print("Are both refs the same? "+(x==y));

+3

Thanx for the help

+2

When a class implements the interface Comparable, it overrides the method equals. Since you can call the method equals on objects of that class, to know whether they are equals or not

0

It might help you to learn more about "pointers" and what's going on with the memory of objects under the hood. You see each instance of an object really only stores an address in memory. (It "points" to the location where all of it's data and methods are stored. Because each instance of a class is assigned it's own memory locations that real...

0

Number is almost guaranteed to be different. Normally, you can test equality with ==, but with objects (instances of a class) this will fail even if everything stored in the class is identical. The "equals()" function is written to laboriouly look up and compare the actual values. If all values match it can come back with true.