为什么.equals方法在两个相同的值对象上失败? [英] Why .equals method is failing on two same value objects?

查看:81
本文介绍了为什么.equals方法在两个相同的值对象上失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个值对象 MarketVO ,并且此值对象的两个实例具有相同的元素和每个元素的相同值。

I have created a value object MarketVO and two instances of this value object have same elements and same value for each element.

我的价值对象类是:

public class MarketVO {

    private double floatAmt;
    private Date marketDate;
    private long marketCap;
}

以下是值:

returnedData:

returnedData:

FloatAmt: 247657.5418618201, MarketCap: 5249164,
MarketDate: 2011-07-29 00:00:00.0 

expectedData:

expectedData:

FloatAmt: 247657.5418618201, MarketCap: 5249164, 
MarketDate: 2011-07-29 00:00:00.0

现在在我的单元测试类中,我想断言我的返回和预期类型是相同的,包含相同顺序的相同值,所以我正在做类似的事情

Now in my unit test class, I want to assert that my returned and expected type is same containing same value in same order so am doing something like

assertTrue(returnedData.equals(expectedData)),现在返回 false 值但是如果我这样做

assertTrue(returnedData.equals(expectedData)), now this is returning false value but if I do

assertEquals(testObject.getfloatAmt(), testObject2.getfloatAmt());
assertEquals(testObject.getmarketCap(), testObject2.getmarketCap());
assertEquals(testObject.getmarketDate(), testObject2.getmarketDate());

此测试通过,所以我不确定为什么 .equals 方法在这里不起作用?有什么建议吗?

this test passes and so am not sure as to why .equals method is not working in here? Any suggestions?

更新:我想在此强调我们正在使用它进行 单元测试 即可。

Update: I want to put emphasize here that we are using this for doing Unit Testing.

推荐答案

.equals 比较对象引用,而不是对象内容。

The default implementation of .equals compares object references, not object content.

您可能希望覆盖equals(和hashCode)方法。这样的事情:

You probably want to override the equals (and hashCode) methods. Something like this:

public class MarketVO {

    private double floatAmt;
    private Date marketDate;
    private long marketCap;

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof MarketVO))
            return false;
        MarketVO other = (MarketVO) o;
        return other.floatAmt == floatAmt &&
               other.marketDate.equals(marketDate) &&
               other.marketCap == marketCap;
    }

    @Override
    public int hashCode() {
        ...
    }
}

这篇关于为什么.equals方法在两个相同的值对象上失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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