ArrayList of my objects, indexOf problem

后端 未结 4 1479
一个人的身影
一个人的身影 2021-01-20 12:04

I have problem with Java\'s ArrayList. I\'ve created an Object, that contains two attributes, x and y. Now I\'ve loaded some object in my ArrayList. Problem is that I don\'t

4条回答
  •  迷失自我
    2021-01-20 12:49

    Is this what you looking for?

    public class Point {
    
    private final int x;
    private final int y;
    
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    public int getX() {
        return x;
    }
    
    public int getY() {
        return y;
    }
    
    @Override
    public boolean equals(Object o) {
        return (o instanceof Point && getX() == ((Point) o).getX() && getY() == ((Point) o)
                .getY());
    
    }
    

    }

    public class TestIndexOf {
    
    public static void main(String[] args){
        Point p1 = new Point(10,30);
        Point p2 = new Point(20,40);
        Point p3 = new Point(50,40);
        Point p4 = new Point(60,40);
        List list = new ArrayList();
        list.add(p1);
        list.add(p2);
        list.add(p3);
        list.add(p4);
        System.out.println(list.indexOf(p3));
    }
    

    }

    If you just want to search on the x property, change the equals method to compare only the x values like:

    @Override
    public boolean equals(Object o) {
        return (o instanceof Point && getX() == ((Point) o).getX());
    
    }
    

提交回复
热议问题