0
Can not understand program output of .equals
there are two classes Class test { A a1= new A(); A a2= new A() System.out.println(a1.equals(a2)); } Class A { Int x=1; } Output is "false" Though the value in a1 and a2 is same Please someone explain
4 odpowiedzi
+ 1
As I said above the default implementation of equals checks whether two objects are referring to the same.
In string class they have implemented (overridden) the equals method to compare string values.
+ 4
whenever new A() is used, it creates a new instance of the object. They can obviously have same methods and variables but still both are different instances of A and hence won't be equal.
+ 1
You have not implemented equals() method in your class A so it will use the default implementation which checks whether two objects refer to the same object.
In this case you're creating two objects(which are clearly two individual objects not one) and using equals method.
As these are two different objects equals method returns false.
If you want to compare two values of the class(for example x) implement your own(override) equals method.
0
But for below
String s1= new String("test")
String s2= new String("test")
System.out.println(s1.equals(s2));
It is showing "true" and both are two different objects then why it is showing true?
Can someone explain this please?