有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Multimap在containsValue()上找到实例,尽管equals()和hashCode()返回不同的值。怎么会这样?

我构建了一个TreeMultimap,并想添加我的Wedge类的实例。但它拒绝添加更多内容。我有点不知所措,因为我已经实现了equalshashCode。更奇怪的是,当我调用调试器中的方法来检查我是否没有出错时,不同对象上的这些方法返回不同的值。因此,安全壳检查结果为真,这似乎很奇怪。下面是一些代码:

@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) 个答案

  1. # 1 楼答案

    TreeMultimap使用Comparable而不是equalshashCode。从JavaDoc:

    Implementation of Multimap whose keys and values are ordered by their natural ordering or by supplied comparators. In all cases, this implementation uses Comparable.compareTo(T) or Comparator.compare(T, T) instead of Object.equals(java.lang.Object) to determine equivalence of instances.