indexOf()将找不到自定义对象类型

aja*_*jay 7 java arraylist indexof

以下代码没有给我正确的答案.

class Point {

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

class A{

    public static void main(String[] args){

        ArrayList<Point> p=new ArrayList<Point>();
        p.add(new Point(3,4));
        p.add(new Point(1,2));
        System.out.println(p.indexOf(1,2));

    }
}
Run Code Online (Sandbox Code Playgroud)

这给了-1;

一般来说,如果给出了arraylist of point,我们怎样才能找到数组中特定点的索引?

ali*_*der 7

indexOf需要对象作为输入.如果找不到要传入的对象,则返回-1.您需要将您要查找的arraylist中的位置作为输入传递给indexOf函数.在这种情况下,您还应该为您的类重写hashcode和equals.

在您的类Point中覆盖hashcode和equals.然后,一旦创建了此类Point的实例(使用new关键字)并将它们添加到arrayList,就可以使用任何Point对象作为indexOf调用的参数对arrayList使用indexOf调用.

类点

public class Point {

        int x; 
        int y;

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

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + x;
            result = prime * result + y;
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Point other = (Point) obj;
            if (x != other.x)
                return false;
            if (y != other.y)
                return false;
            return true;
        }       
}
Run Code Online (Sandbox Code Playgroud)

类测试(你称之为"a"):

import java.util.ArrayList;

public class Test {

     public static void main(String[] args){

            ArrayList<Point> p=new ArrayList<Point>();

            Point p1 = new Point(3,4);
            Point p2 = new Point(1,2);

            p.add(new Point(3,4));
            p.add(new Point(1,2));

            System.out.println(p.indexOf(p1));
     }

}
Run Code Online (Sandbox Code Playgroud)