Java中hashCode有什么用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3563847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:53:35  来源:igfitidea点击:

What is the use of hashCode in Java?

javahashcode

提问by Vinoth Kumar

In Java, obj.hashCode()returns some value. What is the use of this hash code in programming?

在 Java 中,obj.hashCode()返回一些值。这个哈希码在编程中有什么用?

回答by John Topley

From the Javadoc:

Javadoc

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCodeis:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCodemethod must consistently return the same integer, provided no information used in 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.

  • If two objects are equal according to the equals(Object)method, then calling the hashCodemethod on each of the two objects must produce the same integer result.

  • It is notrequired that if two objects are unequal according to the equals(java.lang.Object)method, then calling the hashCodemethod 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 hashtables.

As much as is reasonably practical, the hashCode method defined by class 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 programming language.)

返回对象的哈希码值。支持此方法是为了哈希表,例如由java.util.Hashtable.

总合同hashCode为:

  • 在 Java 应用程序执行期间,只要在同一个对象上多次调用它,该hashCode方法必须始终返回相同的 integer,前提是没有修改对象的 equals 比较中使用的信息。该整数不需要从应用程序的一次执行到同一应用程序的另一次执行保持一致。

  • 如果根据equals(Object)方法两个对象相等,则hashCode对两个对象中的每一个调用该方法必须产生相同的整数结果。

  • 要求,如果两个对象根据是不相等的equals(java.lang.Object)方法,然后调用hashCode在每个两个对象的方法必须产生不同的整数结果。但是,程序员应该意识到为不相等的对象生成不同的整数结果可能会提高哈希表的性能。

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

回答by u290629

Although hashcode does nothing with your business logic, we have to take care of it in most cases. Because when your object is put into a hash based container(HashSet, HashMap...), the container puts/gets the element's hashcode.

尽管 hashcode 对您的业务逻辑没有任何作用,但在大多数情况下我们必须处理它。因为当您的对象被放入基于哈希的容器(HashSet、HashMap...)时,容器会放置/获取元素的哈希码。

回答by aish

hashCode()is used for bucketingin Hashimplementations like HashMap, HashTable, HashSet, etc.

hashCode()用于铲装Hash实现喜欢HashMapHashTableHashSet等。

The value received from hashCode()is used as the bucket numberfor storing elements of the set/map. This bucket number is the addressof the element inside the set/map.

收到的值hashCode()用作存储集合/映射元素的桶号。这个桶号是集合/映射中元素的地址

When you do contains()it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals()method to evaluate if the objects are equal, and then decide if contains()is true or false, or decide if element could be added in the set or not.

当您这样做时contains(),它将获取元素的哈希码,然后查找哈希码指向的存储桶。如果在同一个bucket中发现超过1个元素(多个对象可以有相同的hash码),那么它使用该equals()方法来评估对象是否相等,然后判断contains()是真还是假,或者判断元素是否可以是否在集合中添加。

回答by roottraveller

hashCode()is a function that takes an object and outputs a numeric value. The hashcode for an object is always the same if the object doesn't change.

hashCode()是一个函数,它接受一个对象并输出一个数值。如果对象没有改变,对象的哈希码总是相同的。

Functions like HashMap, HashTable, HashSet, etc. that need to store objects will use a hashCodemodulo the size of their internal array to choose in what "memory position" (i.e. array position) to store the object.

HashMapHashTableHashSet等需要存储对象的函数将使用hashCode其内部数组大小的模来选择在什么“内存位置”(即数组位置)中存储对象。

There are some cases where collisions may occur (two objects end up with the same hashcode), and that, of course, needs to be solved carefully.

在某些情况下可能会发生冲突(两个对象最终具有相同的哈希码),当然,需要仔细解决。

回答by pritish sahu

hashCode()is a uniquecode which is generated by the JVM for every object creation.

hashCode()是JVM 为每个对象创建生成的唯一代码。

We use hashCode()to perform some operation on hashing related algorithm like Hashtable, Hashmap etc..

我们用来hashCode()对散列相关算法(如 Hashtable、Hashmap 等)执行一些操作。

The advantages of hashCode()make searching operation easy because when we search for an object that has unique code, it helps to find out that object.

hashCode()使搜索操作变得容易的优点是,当我们搜索具有唯一代码的对象时,有助于找出该对象。

But we can't say hashCode()is the address of an object. It is a unique code generated by JVM for every object.

但是我们不能说hashCode()是一个对象的地址。它是 JVM 为每个对象生成的唯一代码。

That is why nowadays hashing algorithm is the most popular search algorithm.

这就是为什么现在散列算法是最流行的搜索算法。

回答by Eli

The value returned by hashCode()is the object's hash code, which is the object's memory address in hexadecimal.

By definition, if two objects are equal, their hash code must also be equal. If you override the equals()method, you change the way two objects are equated and Object's implementation of hashCode()is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode()method as well.

返回的值hashCode()是对象的哈希码,也就是对象的16进制内存地址。

根据定义,如果两个对象相等,则它们的哈希码也必须相等。如果重写该equals()方法,则会更改两个对象的等价方式,并且对象的实现hashCode()不再有效。因此,如果您覆盖 equals() 方法,您还必须覆盖该hashCode()方法。

This answer is from the java SE 8 official tutorial documentation

这个答案来自 java SE 8 官方教程文档

回答by Sudabe-Neirizi

One of the uses of hashCode() is building a Catching mechanism. Look at this example:

hashCode() 的用途之一是构建一个捕获机制。看这个例子:

        class Point
    {
      public int x, y;

      public Point(int x, int y)
      {
        this.x = x;
        this.y = y;
      }

      @Override
      public boolean equals(Object o)
      {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Point point = (Point) o;

        if (x != point.x) return false;
        return y == point.y;
      }

      @Override
      public int hashCode()
      {
        int result = x;
        result = 31 * result + y;
        return result;
      }

class Line
{
  public Point start, end;

  public Line(Point start, Point end)
  {
    this.start = start;
    this.end = end;
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Line line = (Line) o;

    if (!start.equals(line.start)) return false;
    return end.equals(line.end);
  }

  @Override
  public int hashCode()
  {
    int result = start.hashCode();
    result = 31 * result + end.hashCode();
    return result;
  }
}
class LineToPointAdapter implements Iterable<Point>
{
  private static int count = 0;
  private static Map<Integer, List<Point>> cache = new HashMap<>();
  private int hash;

  public LineToPointAdapter(Line line)
  {
    hash = line.hashCode();
    if (cache.get(hash) != null) return; // we already have it

    System.out.println(
      String.format("%d: Generating points for line [%d,%d]-[%d,%d] (no caching)",
        ++count, line.start.x, line.start.y, line.end.x, line.end.y));
}

回答by Satyajit Das

A hashcodeis a number generated from any object.

哈希码是从任何对象生成的数字。

This is what allows objects to be stored/retrieved quickly in a Hashtable.

这就是允许对象在 Hashtable 中快速存储/检索的原因。

Imagine the following simple example:

想象一下下面这个简单的例子

On the table in front of you. you have nine boxes, each marked with a number 1 to 9. You also have a pile of wildly different objects to store in these boxes, but once they are in there you need to be able to find them as quickly as possible.

在你面前的桌子上。你有九个盒子,每个盒子都标有数字 1 到 9。你还有一堆截然不同的物品要存放在这些盒子里,但是一旦它们在那里,你需要能够尽快找到它们。

What you need is a way of instantly deciding which box you have put each object in. It works like an index. you decide to find the cabbage so you look up which box the cabbage is in, then go straight to that box to get it.

您需要的是一种立即决定将每个对象放入哪个框的方法。它的工作方式类似于索引。你决定找到卷心菜,所以你查找卷心菜在哪个盒子里,然后直接去那个盒子拿它。

Now imagine that you don't want to bother with the index, you want to be able to find out immediately from the object which box it lives in.

现在想象一下,您不想打扰索引,您希望能够立即从对象中找出它所在的盒子。

In the example, let's use a really simple way of doing this - the number of letters in the name of the object. So the cabbage goes in box 7, the pea goes in box 3, the rocket in box 6, the banjo in box 5 and so on.

在该示例中,让我们使用一种非常简单的方法来执行此操作 - 对象名称中的字母数。所以卷心菜在盒子 7 中,豌豆在盒子 3 中,火箭在盒子 6 中,班卓琴在盒子 5 中,依此类推。

What about the rhinoceros, though? It has 10 characters, so we'll change our algorithm a little and "wrap around" so that 10-letter objects go in box 1, 11 letters in box 2 and so on. That should cover any object.

然而,犀牛呢?它有 10 个字符,所以我们将稍微改变我们的算法并“环绕”,以便 10 个字母的对象进入框 1,11 个字母进入框 2,依此类推。这应该涵盖任何对象。

Sometimes a box will have more than one object in it, but if you are looking for a rocket, it's still much quicker to compare a peanut and a rocket, than to check a whole pile of cabbages, peas, banjos, and rhinoceroses.

有时一个盒子里会有不止一个物体,但如果你正在寻找火箭,比较花生和火箭仍然比检查一整堆卷心菜、豌豆、班卓琴和犀牛要快得多。

That's a hash code. A way of getting a number from an object so it can be stored in a Hashtable. In Java, a hash code can be any integer, and each object type is responsible for generating its own. Lookup the "hashCode" method of Object.

那是一个哈希码。一种从对象中获取数字以便将其存储在哈希表中的方法。在 Java 中,哈希码可以是任何整数,每个对象类型负责生成自己的。查找 Object 的“hashCode”方法。

Source - here

来源 -这里