比较应返回true但返回false

Val*_*lva 0 java debugging comparison if-statement

我有两个相同类型的对象,然后我试图看看它们是否相等,但似乎它们不是,我真的不明白为什么会发生这种情况,我从屏幕上拍了一张照片在哪里你们可以看到我想说的话:

在这里(高分辨率).

图像是为了向你们展示即使是重新布局也会发生什么.

这是代码和类:

private boolean checkForExpr(Type lowerExprType, Type upperExprType) {
    boolean result = false;
    if (lowerExprType == Type.undefinedType || upperExprType == Type.undefinedType){
        return false;
    }else{
        result = (lowerExprType == upperExprType);
    }
        return result;
}
Run Code Online (Sandbox Code Playgroud)

输入类

abstract public class Type {

    public Type( String name ) {
        this.name = name;
    }

    public static Type booleanType = new BooleanType();
    public static Type integerType = new IntegerType();
    public static Type charType    = new CharType();
    public static Type undefinedType = new UndefinedType();

    public String getName() {
        return name;
    }

    abstract public String getCname();

    private String name;
}
Run Code Online (Sandbox Code Playgroud)

IntegerType类

public class IntegerType extends Type {

    public IntegerType() {
        super("integer");
    }

   public String getCname() {
      return "int";
   }

}
Run Code Online (Sandbox Code Playgroud)

And*_*ell 6

您正在检查它是否与同一对象的引用相同.根据你的调试器,他们不是.查看调试器中的(id =)字段.字符串"integer"具有相同的(id =)但您的两个Type对象是不同的.

您需要实现equals和hashCode,然后检查内部对象属性,例如:

abstract public class Type {
    @Override
    public boolean equals(Object obj){
        if (obj instanceof Type) {
            return name.equals (((Type)obj).getName());
        }
        return false;
    }   
}
Run Code Online (Sandbox Code Playgroud)

你应该检查空值等.

看看这个问题的答案覆盖equals方法