Java 获取错误“不兼容类型”

Java 获取错误“不兼容类型”,java,Java,我不熟悉Java编程和测试,它包含ArrayList中使用的方法。当我通过contains方法传递对象时,我重写了Object类的equals方法,但在这样做的同时,我得到了以下错误 不兼容类型:无法将对象转换为检查孔 下面是我编写的代码 import java.util.*; class checkHole { public int a, b; public checkHole (int a, int b) { this.a = a;

我不熟悉Java编程和测试,它包含ArrayList中使用的方法。当我通过contains方法传递对象时,我重写了Object类的equals方法,但在这样做的同时,我得到了以下错误 不兼容类型:无法将对象转换为检查孔

下面是我编写的代码

import java.util.*;

class checkHole
{
    public int a, b;
    public checkHole (int a, int b)
    {
        this.a = a;
        this.b = b;
    }

    public int getA()
    {
        return this.a;
    }

    public boolean equals(Object o)
    {

        if(o instanceof checkHole)
        {
            return ((checkHole)o).getA().equals(this.a);

        }
        else 
            return false;
    }

    public static void main(String args[])
    {
        ArrayList<checkHole> aList = new ArrayList<checkHole>();

        aList.add(new checkHole(0,1));
        aList.add(new checkHole(2,3));
        aList.add(new checkHole(4,5));

        checkHole h = new checkHole(0,1);
        boolean x = aList.contains(h);  // x = true if the objects are equal by value

        System.out.println(x); // Should print true if the objects are equal
    }
}
我一直在寻找关于上述铸造问题相当长的一段时间,但徒劳无功。几乎所有地方都以类似的方式使用equals方法


我不知道为什么我不能将obj转换为checkHole类型。

只需将.Equals更改为==。使用基本类型int、char、boolean时,请使用==。当使用对象引用CheckHole时,您创建的任何类型的类都使用.equals

if(o instanceof checkHole)
{
    return ((checkHole)o).getA()==this.a;
}

发布准确完整的错误消息,并告诉我们它指的是哪一行。另外,适当缩进代码,并遵守Java命名约定:类以大写字母开头。如果对象的值相等,则x=true显然是无效的Java代码。如果这应该是一个注释,那么就把它变成一个注释,就像你在.BTW之后做的那样,也许我写Java代码已经很久了,但是你不应该在使用int等基本类型时使用“==”操作符而不是equals方法吗?所以checkHoleo.getA==this.aI没有ide,但似乎您正在对int基元类型调用equals,这可能会导致问题这是您的代码的精确副本吗?正如其他人所提到的,它无法编译,因为它试图调用一个基元类型int上的方法equals。除此之外,它可以按预期工作。