1

I have this code for Point class

public class Point {
   private int x, y;

   public Point(int x, int y) {
       this.x = x;
       this.y = y;
   }
   public void setX(int x) {
       this.x = x;
   }
   public void setY(int y) {
       this.y = y;
   }
}

In other class, inside a method I have

ArrayList<Point> points = new ArrayList<Point>();
Point p = new Point(1, 2);
points.add(p);

Now I want to remove this Point p I just added

Point toRemove = new Point(0, 0);
toRemove.setX(1);
toRemove.setY(2);

points.contains(toRemove);
points.remove(toRemove);

And the contains prints false and the Point is not removed from the ArrayList. How can I remove using an object?

Arthur
  • 171
  • 6
  • 5
    You need to override `equals` method in your `Point` class as its code is used while searching for equal objects. And since we are overriding `equals` we also should override `hashcode` method. – Pshemo May 27 '21 at 19:50
  • 2
    @Arthur - Pshemo is correct. If you kept a reference to your original object, "p", then `points.contains(p);` and `points.remove(p);` would behave as you expect. But you created a *DIFFERENT* "Point" object. So the arraylist has no clue that "toRemove" has anything to do with "p", even though X and Y happen to be the same. The solution is to override "equals". Look here: [Java Collections – How to Override equals() and hashcode() Method in Java](https://crunchify.com/how-to-override-equals-and-hashcode-method-in-java/) – paulsm4 May 27 '21 at 19:57
  • Thanks @Pshemo . I did override and its working ! – Arthur May 27 '21 at 19:58
  • Thanks for the link @paulsm4 – Arthur May 27 '21 at 19:59

0 Answers0