2

I am using the contains method to check whether given coordinates are present in the list or not. The output of the above code should be "Yes" but I am getting "NO". Can anybody help me with this?

class points {
    
    public int x;
    
    public int y;
    
    public points(int x,int y){
        this.x=x;
        this.y=y;
    }
}

class GFG {
     public static void main (String[] args) {
         ArrayList<points> point = new ArrayList<points>();
         points p= new points(1,1);
         points q= new points(2,2);
         point.add(p);
         point.add(q);
         if(point.contains(new points(1,1))){
            System.out.println("Yes");
         }
         else{
            System.out.println("NO");``
         }
     }
}
M. Deinum
  • 115,695
  • 22
  • 220
  • 224

2 Answers2

1

X and Y coordinates are same for the objects you are comparing but, objects are different than each other. Please see below screen shot, while debugging, you can see object's id. And even though coordinates are same, objects are different:

p is Main$points@487 but sameOrNot is Main$points@489. So since you are comparing directly objects, result is false.

enter image description here

To achieve what you want to do, you need to override equals() and hashCode() in your class to specify that when coordinates are same, objects are same:

class points{
    public int x;
    public int y;

    public points(int x,int y){
        this.x=x;
        this.y=y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        points points = (points) o;
        return x == points.x &&
                y == points.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}
Sercan
  • 2,081
  • 2
  • 10
  • 23
0

From java documentation for the contains method:

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

You have not overriden your points class methods equals and hashcode so the contains method still refers to the Object equals method; so you are comparing two different references to two objects with equal coordinates and then explained the negative result for contains.

dariosicily
  • 4,239
  • 2
  • 11
  • 17