Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the reason why HashCode uses 31 as a multiplier

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the reason why HashCode uses 31 as a multiplier". The explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the reason why HashCode uses 31 as a multiplier"?

Source code explanation 1. The fixed product 31 uses / / to get hashCode "abc" .hashCode ()

Public int hashCode () {

Int h = hash

If (h = = 0 & & value.length > 0) {

Char val [] = value

For (int I = 0; I < value.length; iTunes +) {

H = 31 * h + val [I]

}

Hash = h

}

Return h

}

In getting the source code of hashCode, you can see that there is a fixed value 31, which is calculated by the product each time the for loop is executed, and the formula after the loop is as follows: s [0] * 31 ^ (nmur1) + s [1] * 31 ^ (NMu2) +. + s [n-1]

"so why did you choose 31 as the product value? "

two。 Answer from stackoverflow

In stackoverflow, there is a discussion article about why 31 is chosen as the fixed product value, Why does Java's hashCode () in String use 31 as a multiplier? This is a question that has been around for a long time. Pick two of the most liked questions.

"413 likes? The answer. "

The most common answer is from the content of "Effective Java"

The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * I = (I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report