我构建了一个TreeMultimap
,并希望添加一个Wedge
类的实例。但它拒绝增加不止一个。因为我实施了equals
和hashCode
,我感到很遗憾。更奇怪的是,当我调用调试器中的方法来检查我是否没有出错时,单独对象上的这些方法返回不同的值。因此,对包含的检查返回true似乎很奇怪。这里有一些代码:
@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
变量包含不同的coronas实例,因为在循环中调用该方法以添加所有Corona
个实例。
现在,只要我添加第一个Wedge
测试,如coronas.containsValue(corona)
,即使我构造了一个新的Wedge
实例并将其传递给方法,也会返回true。如前所述,使用corona.equals(coronaInTheMap)
或corona.hashCode() == hashCodeOfCoronaInMap
的测试会返回不同的值。
描述在构造函数中设置,永远不会被修改!
我已经搜索了错误,但是我很沮丧。我需要你的协助!
答案 0 :(得分:3)
TreeMultimap
使用Comparable
而不是equals
和hashCode
。来自JavaDoc:
Multimap的实现,其键和值按其排序 自然排序或由提供的比较器。在所有情况下,这 实现使用Comparable.compareTo(T)或Comparator.compare(T, T)代替Object.equals(java.lang.Object)来确定等价 实例。