indexOf()将找不到自定义对象类型 [英] indexOf() will not find a custom object type

查看:218
本文介绍了indexOf()将找不到自定义对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following code does not give me right answer.

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));

    }
}

这给出 -1 ;

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

In general if arraylist of point is given, how can we find index of a particular point in in array ?

推荐答案

indexOf需要对象作为输入。如果找不到要传入的对象,则返回-1。您需要将您要查找的arraylist中的位置作为输入传递给indexOf函数。在这种情况下,您还应该覆盖您的类的哈希码和等号。

indexOf requires the object as input. If it does not find the object you are passing in, it will return -1. You need to pass the object whose location in the arraylist you are looking for as the input into the indexOf function. You should also override hashcode and equals for your class in this case.

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

Override hashcode and equals in your class Point. Then once you create instances of this class Point (using the new keyword) and add them to the arrayList, you can use the indexOf call on the arrayList using any of the Point objects as a parameter to the indexOf call.

Class Point

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;
        }       
}

Class Test(你称之为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));
     }

}

这篇关于indexOf()将找不到自定义对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆