0

I cant under stand why and when we use this method?

Please some oee explain this lesson to me!

16th Mar 2017, 7:02 AM
ali lashkari
ali lashkari - avatar
1 Odpowiedź
+ 6
examine the following example: String s1 = new String( "my string" ); String s2 = new String( "my string" ); System.out.println(s1 == s2); // false System.out.println(s1.equals(s2)); // true the reason that the == comparison returns false is because it compare the references of the objects rather than checking their values, which is what equals do in this case another example could be overriding the equals method for your own class: public class Point{ private int x; private int y; public Point( int x, int y) { this.x = x; this.y = y; } public boolean equals(Object o) { if (!(o instanceof Point)) { return false; } return (x==((Point)o).x&&y==((Point)o).y); } } in this case, overriding equals would be the best solution to compare 2 Point instances, as they will check each instance x,y value and compare them while using == will simply compare the reference
16th Mar 2017, 7:55 AM
Burey
Burey - avatar