0
What is the advantage of the "equals"-method over using the point notation in comparison of values?
Can somebody please explain to me, why we need the "equals" method? Isn't it possible to access and compare the attributes of two instances of the same class by using the point notation (see example code below)? What is the advantage of the "equals"-method? Example Code: public class MyClass { public static void main(String[ ] args) { class Animal { String name; Animal(String n) { name = n; } } Animal a1 = new Animal("Robby"); Animal a2 = new Animal("Robby"); System.out.println(a1 == a2); System.out.println(a1.name == a2.name); } } // output of first comparison: false // output of second comparison: true
2 Answers
+ 3
Basically equals does the exact same thing like you did in your second SOUT. Equals compares the Member-Variables while the == operator compares the place where your object is allocated in your RAM.
+ 1
equals method would be less lines of code and more efficient as well as easier to read