我的代码发生了一个奇怪的问题:
RestAPIHeader requestedBy = new RestAPIHeader("X-Requested-By", "test");
// Act
RestAPIRequest req = prepareLoginRequest(USER_NAME, PASSWORD);
// The following returns a list of header objects such that one of them
// is "X-Requested-By: test"
List<RestAPIHeader> headers = req.getAllHeaders();
boolean foundRequestedBy = false;
for (RestAPIHeader h : headers) {
Log.d(LOGTAG, "Header: " + h.toString());
if (requestedBy.equals(h)) {
foundRequestedBy = true;
}
}
// Assert
assertNotNull(req);
// This assertion passes
assertTrue(foundRequestedBy);
// This assertion fails
assertTrue(headers.contains(requestedBy));
让我困扰的是,在这段代码中headers.contains(requestedBy)
似乎应该等同于foundRequestedBy
(因为这是简单搜索的结果)。但是,正如我在评论中提到的那样,它实际上并没有返回相同的值。似乎contains
似乎没有使用equals()
,而是==
。有人能指出为什么会这样吗?
修改:
equals
类的RestAPIHeader
方法如下:
public boolean equals(RestAPIHeader aOther) {
return mPropertyName.equals(aOther.getHeaderName())
&& mPropertyValue.equals(aOther.getHeaderValue());
}
答案 0 :(得分:10)
等于的签名是
public boolean equals(Object o);
所以你的等于方法
public boolean equals(RestAPIHeader aOther);
是一个重载,而不是覆盖。 contains例程不会调用此重载。所以你只需要将签名更正为
public boolean equals(Object o) {
if(!(o instanceof RestAPIHeader))
return false;
RestAPIHeader aOther = (RestAPIHeader)o;
/* same as yours from here */
答案 1 :(得分:2)
实施平等的正确方法是:
@Override
public boolean equals(Object aOther) {...
而不是public boolean equals(RestAPIHeader aOther)