checking if list contains the object – java
checking if list contains the object – java
You need to override equals
on your Point
class. Your Point
class must be responsible for determining whether another Point
object is equal to the current object. An ArrayList
will call equals
to determine if the object passed in to contains
is equal to any item in the list.
If you dont override equals
, then Point
will inherit equals
from Object
, which will simply see if its the same exact object. Thats why your first code works, because you are re-using first
. It also explains why your second code doesnt work, because you used a different object.
Also, if you override equals
, its best to override hashCode
also (and vice versa).
List determine whether two objects are equal by using equals
method.
If your class wont override public boolean equals(Object o){..}
method, it will will inherit it from closest supertype which provides that implementation.
If your class doesnt extend any other class, it will means it implicitly extends Object
class. So it will inherit equals
implementation from it. Problem is that this implementation looks like:
public boolean equals(Object obj) {
return (this == obj);
}
so it uses reference equality operator ==
. This means that equals
will only return true if object will be compared with itself (references to other objects will always be different than reference to this
object).
In your case your equals method to return true
also for other instances of Point1
if their state (value of x
and y
) is equal.
@Override
public boolean equals(Object other) {
if(this == other)
return true;
if(!other instanceof Point1)
return false;
Point1 otherPoint= (Point1)other;
if(this.x == otherPoint.getX() && this.y == otherPoint.getY())
return true;
return false;
}
And you can get the result you want:
BTW while overriding equals
method we should also override hashcode
method. See Why do I need to override the equals and hashCode methods in Java?