Home >Java >javaTutorial >How does the `hashCode()` method behave in Java when it\'s not overridden?

How does the `hashCode()` method behave in Java when it\'s not overridden?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 00:36:02918browse

How does the `hashCode()` method behave in Java when it's not overridden?

Object Hash Code Default Behavior in Java

If the hashCode() method is not explicitly overridden in a Java object, invoking hashCode() on that object yields a specific result based on the implementation of the Java Virtual Machine (JVM).

HotSpot JVM Default Behavior

In the HotSpot JVM, the default behavior is as follows:

  • First invocation: A random number is generated and stored in the object header.
  • Subsequent invocations: The random number is extracted from the object header.

By default, this random number has no correlation with the object's contents or location.

Customizable Behavior

The behavior of the hashCode() method can be customized using the -XX:hashCode=n HotSpot JVM option. This option takes the following values:

  • 0: Global random generator (default in Java 7)
  • 5: Thread-local xor-shift random generator (default in Java 8)
  • 1: Object pointer mixed with a random value (stable between stop-the-world events)
  • 2: Always 1
  • 3: Autoincrementing numbers
  • 4: Object pointer trimmed to 32 bits

Special Considerations

  • Even with -XX:hashCode=4, the hash code may not always point to the object address. Objects can be moved after creation, but the hash code remains unchanged.
  • Object addresses may be poorly distributed, leading to unbalanced hash tables when using the -XX:hashCode=4 option.

The above is the detailed content of How does the `hashCode()` method behave in Java when it's not overridden?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn