Equals() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Equals()

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

16th Mar 2019, 6:38 AM
Jonny Walker
Jonny Walker - avatar
7 Answers
+ 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
16th Mar 2019, 7:06 AM
Tashi N
Tashi N - avatar
+ 7
The equals method compares the value of two variables, and returns true if they are equal, and false if they’re not.
16th Mar 2019, 7:07 AM
Rowsej
Rowsej - avatar
+ 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));
16th Mar 2019, 8:54 AM
D_Stark
D_Stark - avatar
+ 3
Thanx for the help
20th Mar 2019, 6:04 AM
Jonny Walker
Jonny Walker - avatar
+ 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
17th Mar 2019, 7:15 AM
Abel Bakomen nana
Abel Bakomen nana - avatar
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...
22nd Apr 2019, 3:24 PM
James McLain
James McLain - avatar
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.
22nd Apr 2019, 3:30 PM
James McLain
James McLain - avatar