Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

java - Why .equals method is failing on two same value objects?

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

My value object class is:

public class MarketVO {

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

Here are the values:

returnedData:

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

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)), 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());

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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() {
        ...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...