繁体   English   中英

Java对象相等不起作用

[英]java object equality not working

我确实尝试在该论坛中搜索此类问题的答案,但到目前为止,似乎都没有任何结果。

我想输入检查方法声明,例如:

public int stackOverFlow() {int a; a = a + 1; return 0;}

返回表达式的类型必须与方法的返回类型匹配(在本示例中为true)。

我使用Java Tree Builder为语法中的所有非终结符(以节点的形式)和默认的深度优先访问者生成语法树。

我有一个实现Node接口的MethodDeclaration类。 节点接口具有以下形式的accept方法:

public Node accept(TypeVisitor v){ return v.visit(v));

此accept方法使TypeVisitor可以访问MethodDeclaration。

现在访问方法声明,我做一个简单的类型检查

public Node visit(MethodDeclaration n){

    // this visits the f10 Node, which is the return expression, 
    // and returns a specific Node object
    Node rtype =  n.f10.accept(this);

    // this also does a similar thing by visitng the f1 Node,
    // the method's return type, and returns a  specific Node Object
    Node acType = n.f1.accept(this); 

    // Now if I compare the two specific Node objects, it always fails.

    if(rtype == acType){    
        //enter here    
     }
}

为什么不进入if-body? 我还尝试了rtype.equals(acType) ,它返回false。

我尝试了rtype.toString.equals(acType.toString()) ,它也返回false。

我尝试使用eclipse调试器进入代码,这是输出:

rtype   IntegerType  (id=67)    
acType  IntegerType  (id=69)    

从调试器输出可以看出,rtype和acType都是IntegerType对象。

知道为什么比较失败吗?

如果我使用if(rtype instanceof IntegerType),则返回true,并且

如果我使用if(acType instanceof IntegerType),这也将返回true。

但是对象比较总是失败吗?

我正在使用JavaCC(用于生成解析器),JTB(AST和Visitors创建者),eclipse和Java 1.7

在Java中, ==测试对象身份 -实际上,两个对象是同一对象。 您想使用.equals()测试对象相等性 请注意,默认实现(在equals() Object中只是== ;如果要逻辑相等,则您的类必须重写equals(Object)

有关如何执行此操作的资源很多。 本文和Oracle的Java教程都是一个很好的起点。

我看到两个潜在的问题:

(1) rtype == acType很少是您想要的。 使用equals 但是,由于您告诉过您已经使用过它并且没有帮助,所以这是第二个问题:

(2) equals的定义不是您认为的那样,或者值不是您认为的那样。 首先,打印rtype.getClass()acType.getClass()以找出对象的确切类型。 然后获取这些类的源代码(假设您使用的库是开源的),并查看如何定义其equals方法。 然后继续通过equals方法检查要比较的字段的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM