[英]What is the time complexity of Java hashCode method for the String class?
Is Java's hashCode method for String class computed in constant time or linear time? Java 的 String 类的 hashCode 方法是以常数时间还是线性时间计算的? What is the algorithm used?使用的算法是什么?
The documentation tells you the function:文档告诉你这个功能:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
It's computed once using a linear-time pass, and then cached so it's only O(1) to retrieve it in the future.它使用线性时间传递计算一次,然后缓存,以便将来检索它只需 O(1)。
public int hashCode()公共 int hashCode()
Returns a hash code for this string.返回此字符串的哈希码。 The hash code for a String object is computed as String 对象的哈希码计算如下
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
As you can see, the time complexity is the O(n) where n is the number of characters in the string.如您所见,时间复杂度为 O(n),其中 n 是字符串中的字符数。 After one pass, it is cached so the time complexity is effectively O(1).经过一次后,它被缓存,因此时间复杂度实际上是 O(1)。
Time Complexity of Object::hashCode
method is O(1), because it has no any interaction with the data of your object. Object::hashCode
方法的时间复杂度为 O(1),因为它与对象的数据没有任何交互。 It is a native method and written with C language.它是一种本地方法,用 C 语言编写。 The integer value which is returned, is probably heap memory address with some modifications (bitwise operations) since every address in memory representing unique value.返回的整数值可能是经过一些修改(按位运算)的堆内存地址,因为内存中的每个地址都代表唯一值。
For example 4GB memory addresses will be represented in hexadecimal format from 0x00000000
to 0xffffffff
range and each of this value is unique.例如,4GB 内存地址将以十六进制格式表示,从0x00000000
到0xffffffff
范围,并且每个值都是唯一的。 Thus, Java does not require extra computation to ensure uniqueness of these values.因此,Java 不需要额外的计算来确保这些值的唯一性。 Therefore hashCode
gives constant time complexity.因此hashCode
给出了恒定的时间复杂度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.