HashSet或HashMap没有在新类中定义hashCode()方法

时间:2016-09-24 20:18:54

标签: java hashmap hashcode hashset

  • 如果您设计一个新类并尝试在不定义hashCode()方法的情况下将该类的对象插入HashSet或HashMap,会发生什么?

请保持简单说明。我正在攻读考试,而且我仍然因为Java中的哈希而生气。谢谢。

2 个答案:

答案 0 :(得分:1)

HashMap将数据存储到多个单链接的条目列表(也称为存储桶或容器)中。所有列表都在Entry(Entry []数组)

的数组中注册

下图显示了具有可为空条目数组的HashMap实例的内部存储。每个条目都可以链接到另一个条目以形成链接列表。

当用户调用put(K键,V值)或get(Object键)时,该函数计算条目应该在其中的桶的索引。 enter image description here

使用密钥的哈希码生成桶(链表)的该索引。 因此,如果您重写了hashCode方法,它将使用重写方法来计算存储区的索引 否则使用默认哈希码,它是您对象的内存地址。因此,在这种情况下,即使是您的对象,您也会在地图中有一个新条目。因此,即使您尝试存储逻辑上相同的对象。它们将通过哈希映射重新标记为不同。

尽可能合理,但Object类定义的hashCode方法确实为不同的对象返回不同的整数。 (这通常通过将对象的内部地址转换为整数来实现,但JavaTM编程语言不需要此实现技术。)

例如:

MyObject a = new MyObject("a", 123,"something");
MyObject b = new MyObject("a", 123,"something");
a and b will have different hashcodes.

答案 1 :(得分:0)

什么都不会发生: - )

每个对象都有自己的hashCode()方法,该方法继承自 Object 类。因此,您的每个新对象都将是唯一的。通过HashSet或HashMap,它们将被识别为唯一的。

以下是官方评论:

/**
 * Returns a hash code value for the object. This method is
 * supported for the benefit of hash tables such as those provided by
 * {@link java.util.HashMap}.
 * <p>
 * The general contract of {@code hashCode} is:
 * <ul>
 * <li>Whenever it is invoked on the same object more than once during
 *     an execution of a Java application, the {@code hashCode} method
 *     must consistently return the same integer, provided no information
 *     used in {@code equals} comparisons on the object is modified.
 *     This integer need not remain consistent from one execution of an
 *     application to another execution of the same application.
 * <li>If two objects are equal according to the {@code equals(Object)}
 *     method, then calling the {@code hashCode} method on each of
 *     the two objects must produce the same integer result.
 * <li>It is <em>not</em> required that if two objects are unequal
 *     according to the {@link java.lang.Object#equals(java.lang.Object)}
 *     method, then calling the {@code hashCode} method on each of the
 *     two objects must produce distinct integer results.  However, the
 *     programmer should be aware that producing distinct integer results
 *     for unequal objects may improve the performance of hash tables.
 * </ul>
 * <p>
 * As much as is reasonably practical, the hashCode method defined by
 * class {@code Object} does return distinct integers for distinct
 * objects. (This is typically implemented by converting the internal
 * address of the object into an integer, but this implementation
 * technique is not required by the
 * Java&trade; programming language.)
 *
 * @return  a hash code value for this object.
 * @see     java.lang.Object#equals(java.lang.Object)
 * @see     java.lang.System#identityHashCode
 */
public native int hashCode();