Java中的哈希码的用途是什么?

发布于 2025-02-08 16:59:42 字数 62 浏览 2 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

稚然 2025-02-15 16:59:42

hashcode()用于 bucketing hash实现中,例如hashmaphashtablehashset等。

hashcode()接收到的值作为存储设置/映射的元素的 bucke number 。此存储桶号是集合/地图内部元素的地址

当您执行contains()时,它将采用元素的哈希代码,然后查找桶中的哈希代码点。如果在同一存储桶中找到了超过1个元素(多个对象可以具有相同的哈希代码),则它使用equals()方法来评估对象是否相等,然后决定<<<<代码> contains()是对还是错,或者决定是否可以在集合中添加元素。

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

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

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.

兮子 2025-02-15 16:59:42

来自 javadoc

返回对象的哈希代码值。支持此方法的利益,例如java.util.hashtable

提供的方法。

hashcode的一般合同是:

  • 每当在执行Java应用程序时多次在同一对象上调用它时,HashCode方法必须始终返回提供的相同整数在对象上的比较中没有使用任何信息。从一个执行应用程序执行到另一个应用程序的另一个执行,此整数不必保持一致。

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

  • 不是要求如果两个对象根据equals(java.lang.object)不等,则需要调用hashcode两个对象中每个对象的方法都必须产生不同的整数结果。但是,程序员应意识到,为不平等对象产生不同的整数结果可能会提高Hashtables的性能。



尽管合理实用,class对象定义的HashCode方法确实会返回不同对象的不同整数。 (这通常是通过将对象的内部地址转换为整数的,但是Java编程语言不需要此实现技术。)

From the 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 hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method 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 hashCode method on each of the two objects must produce the same integer result.

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

〗斷ホ乔殘χμё〖 2025-02-15 16:59:42

HashCode()是一个获取对象并输出数字值的函数。如果对象不更改,则对象的哈希码始终相同。

HashmapHashtableHashSet等功能,需要存储对象的功能将使用hashcode modulo the size size他们的内部数组要在哪个“内存位置”(即数组位置)中选择以存储对象。

在某些情况下,可能会发生碰撞(两个对象最终以相同的哈希码出现),当然,需要仔细解决。

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.

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

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.

如果没有 2025-02-15 16:59:42

hashcode()返回的值是对象的哈希代码,它是六二铁中对象的内存地址。

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

此答案来自Java SE 8官方教程文档

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.

This answer is from the java SE 8 official tutorial documentation

女皇必胜 2025-02-15 16:59:42

hashcode 是从任何对象生成的数字。

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

想象以下简单示例

在您面前的桌子上。您有九个盒子,每个盒子都标有数字1到9的标记。您还可以在这些盒子中存储一大堆不同的对象,但是一旦它们在那里,您就需要能够尽快找到它们。

您需要的是立即确定将每个对象放入哪个盒子的方法。它的工作方式就像索引。您决定找到白菜,以便查找白菜所在的哪个盒子,然后直接转到该盒子以获取它。

现在想象一下,您不想打扰索引,您希望能够立即从它所居住的对象中找到答案。

在示例中,让我们使用一种非常简单的方式来执行此操作 - 字母数量以对象的名义。因此,卷心菜进入方框7中,豌豆进入方框3,框6中的火箭,方框5中的班卓琴等等。

但是,犀牛呢?它有10个字符,因此我们将对算法进行一些更改,并“缠绕”,以便将10个字母的对象放在Box 1、11个字母中的Box 2等。应该涵盖任何对象。

有时,一个盒子里有一个以上的物体,但是如果您正在寻找火箭,比较花生和火箭要快得多,而不是检查一堆卷心菜,豌豆,班把面和犀牛。

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

来源 - 在这里

A hashcode is a number generated from any object.

This is what allows objects to be stored/retrieved quickly in a 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.

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.

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.

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.

Source - here

痴情 2025-02-15 16:59:42

尽管HashCode对您的业务逻辑没有任何作用,但在大多数情况下,我们必须照顾它。因为当将对象放入基于哈希的容器中(hashsethashmap ...)时,容器puts/for元素的哈希码。

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.

江湖彼岸 2025-02-15 16:59:42

hashcode() unique 代码,由JVM生成每个对象创建。

在哈希相关算法上执行一些操作,例如hashtable,hashmap等。

我们使用hashcode() 具有唯一代码的对象有助于找出该对象。

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

这就是为什么当今哈希算法是最受欢迎的搜索算法的原因。

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

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

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.

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

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

心欲静而疯不止 2025-02-15 16:59:42

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));
}

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

        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));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文