I have got a list of pairs how can i check whether the list contains a specific element or not.The list.contains function is always giving false

SHIVANSH NARAYAN :

I have created a pair class and list of objects of this class. how can i check whether the list contains a object or not

i have tried list.contains method

//the pair class

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

    public int getY() {
        return y;
    }

    public int getX() {
        return x;
    }
}

//this line is always giving false as output

if (!l.contains(new pair(x-1,y)))
                count_1++;
MeetTitan :

By default, objects in Java are only equal if the instances are the same (when you say new Pair() you're making a new instance!).

We can override this behavior by overriding the equals() method of your Point class. Like so:

public class Point {
    private final x;
    private final y;

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

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    private static boolean isPoint(Object o) {
        return o != null && o instanceof Point;
    }

    private boolean coordsEqual(Point p) {
        return getX() == p.getX() && getY() == p.getY();
    }

    public boolean equals(Object o) {
        return isPoint(o) && coordsEqual((Point) o); //is o is a point? Does it have equal coords?
    }

Now Point.equals() will return true if our coordinates match instead of the default object equals behavior. Since Collection.contains() uses the equals() method to check for equality, your code will behave as expected.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=150025&siteId=1