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

查看:35
本文介绍了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,我们如何在数组中找到特定点的索引?

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

推荐答案

indexOf 需要对象作为输入.如果它没有找到您传入的对象,它将返回 -1.您需要将您正在查找的数组列表中位置的对象作为输入传递给 indexOf 函数.在这种情况下,您还应该覆盖您的类的 hashcode 和 equals.

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.

课程点

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

课堂测试(你称之为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天全站免登陆