cobie
cobie

Reputation: 7271

Java Contains method returns false even after defining equals

I have a coordinate class and a list of coordinates. I have overriden the equals method for the coordinate class but when I use the contains on a list of coordinates I get false for a coordinate which is in the list. Has anyone got an idea where I am going wrong? x and y values are ints.

public boolean equals(Coordinate c){
        return (this.x == c.getxCoordinate() && this.y == c.getyCoordinate());
    }

The list is below:

List safe_locs = new ArrayList<Coordinate>();

The test is below:

System.out.println(c);
System.out.println(safe_locs.contains(c));
System.out.println(safe_locs);

output is:

Coordinate[x: 0, y: 0]
false
[Coordinate[x: 0, y: 0], Coordinate[x: 1, y: 0], Coordinate[x: 0, y: 1], Coordinate[x: 3, y: 0], Coordinate[x: 0, y: 3]]

Upvotes: 1

Views: 619

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200206

I am aware that many readers will find this equals implementation style unacceptably condensed, but equals is a very standard, all-boilerplate method and, once you implement a couple hundred of them, you tend to appreciate this style more and more:

@Override
public boolean equals(Object o) {
   Coordinate that;
   return this == o || o instanceof Coordinate 
     && this.x == (that = (Coordinate)o).getxCoordinate() 
     && this.y == that.getyCoordinate();
}

The point is, whatever implementation style you consistently use, you soon stop looking at the detailed program logic and only notice the salient features: what fields participate and by what means they are compared. As soon as you reach that point, the conciceness of this implementation shines. And if you're suspecting a bug, again—less code, less work to check it.

Upvotes: 2

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

I think you have overloaded the equals() method instead of overriding it..

public boolean equals(Object o){

    if(!(o instanceof Coordinate)) {

        return false;
    }
    else{
    Coordinate c = (Coordinate)o;
    return (this.x == c.getxCoordinate() && this.y == c.getyCoordinate());
    }

    }

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340883

Your equals() method is overloading equals(Object), while it should override it:

@Override
public boolean equals(Object o){
    if(!(o instanceof Coordinate)) {
        return false;
    }
    Coordinate c = (Coordinate)o;
    return (this.x == c.getxCoordinate() && this.y == c.getyCoordinate());
    }

Unfortunately you must use downcasting. Notice the @Override annotation - use it in the future to avoid such problems.

Upvotes: 9

Related Questions