Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-11-03 00:36:02
Original
839 people have browsed it

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!