java Multimap在containsValue()上找到实例,尽管equals()和hashCode()返回不同的值。怎么会这样?
我构建了一个TreeMultimap
,并想添加我的Wedge
类的实例。但它拒绝添加更多内容。我有点不知所措,因为我已经实现了equals
和hashCode
。更奇怪的是,当我调用调试器中的方法来检查我是否没有出错时,不同对象上的这些方法返回不同的值。因此,安全壳检查结果为真,这似乎很奇怪。下面是一些代码:
@NonNullByDefault
public class Wedge extends Corona
{
/** Field of the description to display for the wedge. */
private String description;
//Fields and other unrelated methods.
/**
* {@inheritDoc}<br><br>
* Method for determining if both coronas are equal.
* Returns true if both share the same description.
*/
@Override
public boolean equals(@Nullable Object object)
{
if(object == null) return false;
if(object == this) return true;
if(object instanceof Wedge)
{
return description.equals(((Wedge) object).description);
}
return false;
}
/**
* {@inheritDoc}<br><br>
* Method for determining the hash code based on the description.
*/
@Override
public int hashCode()
{
return description.hashCode();
}
}
在简化代码中,使用的代码大致如下:
/** The visual components to display as part of the widget. It's background. */
public Multimap<Integer, Corona> coronas = TreeMultimap.create();
// More interesting fields and methods.
/**
* Method for adding a corona to a given handle.
* @param handleID
* The identifier of the handle for which to add the corona.
* @param corona
* The corona to display on the handle.
* @return
* An instance of the builder for chain calling.
*/
@SuppressWarnings("unchecked")
public B withCorona(int handleID, Corona corona)
{
coronas.put(handleID, corona);
return (B) this;
}
代码是生成器对象的一部分。请原谅这些仿制药handleID
是我用来绑定corona实例的一个键。它的行为符合预期。变量corona
包含不同的coronas实例,因为该方法在循环中被调用以添加所有Corona
实例
现在,只要我添加第一个Wedge
测试,比如coronas.containsValue(corona)
,就会返回true,尽管我构造了一个新的Wedge
实例并将其传递给该方法。如前所述,使用corona.equals(coronaInTheMap)
或corona.hashCode() == hashCodeOfCoronaInMap
的测试返回不同的值
描述在构造函数中设置,从不修改
我找遍了错误,但被踩了。我需要你的帮助
# 1 楼答案
TreeMultimap
使用Comparable
而不是equals
和hashCode
。从JavaDoc: