0
Comparing object.
can someone explain to me why this method is FALSE? class Animal { String name; Animal(String n) { name = n; } } class MyClass { public static void main(String[ ] args) { Animal a1 = new Animal("Robby"); Animal a2 = new Animal("Robby"); System.out.println(a1 == a2); } }
1 ответ
+ 2
1. Point: Equals for OBJECTS means "the same object"
But you have two differend objects.
2. If you do it like this:
Animal a1 = new Animal("Robby");
Animal a2 = a1;
System.out.println(a1 == a2);
Then you will get true, Because it's only one object in two differend variables.
3. To compare objects, you should use the .equals() method.
a1.equals(a2)
4. Why is .equals() better? Because you can override the equals method of your class, and define when two objects of this class should be equal or not.
https://www.baeldung.com/java-comparing-objects