⬅ Previous Topic
Java StringgetChars()
methodNext Topic ⮕
Java StringindexOf()
methodhashCode()
method⬅ Previous Topic
Java StringgetChars()
methodNext Topic ⮕
Java StringindexOf()
methodThe hashCode()
method in Java is a crucial part of working with collections like HashSet
and HashMap
. It generates an integer representation of a string object. This integer value isn't unique to the string itself (collisions are possible), but it’s used as a starting point for efficiently locating objects within these data structures. Think of it like assigning each book in a library a shelf number – multiple books might end up on the same shelf, but that shelf number helps you quickly narrow down your search.
public int hashCode()
Parameter | Description |
---|---|
None | This method takes no arguments. |
The hashCode()
method returns an integer representing the hash code value for this string.
This example demonstrates how to obtain a simple hash code from a String object. It's useful for understanding that even basic strings have a generated integer representation.
public class ExampleOne {
public static void main(String[] args) {
String str = "Hello";
int hashCode = str.hashCode();
System.out.println("The hash code for '" + str + "' is: " + hashCode);
}
}
The hash code for 'Hello' is: -2051793468
Explanation: The `hashCode()` method calculates an integer representation of the string "Hello". This value will likely be different each time you run the program, as it depends on internal factors and potentially JVM implementation. Note that this hash code is based on the contents of the String object.
This example shows how hash codes can be used to compare two strings for equality (though a proper equals()
check is still crucial). Identical strings should produce identical hash codes. Note that unequal string do not necessarily mean that their hashcodes are different.
public class ExampleTwo {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "Java";
String str3 = new String("Java"); // Created using the constructor.
System.out.println("Hash code of '" + str1 + ": " + str1.hashCode());
System.out.println("Hash code of '" + str2 + ": " + str2.hashCode());
System.out.println("Hash code of '" + str3 + ": " + str3.hashCode());
}
}
Hash code of 'Java': 67490752
Hash code of 'Java': 67490752
Hash code of 'Java': 67490752
Explanation: Here, both `str1` and `str2`, which are String literals, have the same hash code. Even when we create a new string object with the exact same content (using the constructor), its hashcode is also identical to the other strings. This highlights that equal strings *should* have equal hash codes.
This example illustrates that different strings can produce the same hash code, which is known as a collision. While hashCode aims for distribution, collisions are inevitable due to the limited integer range and the potentially infinite number of strings.
public class ExampleThree {
public static void main(String[] args) {
String str1 = "ABC";
String str2 = "BCA";
System.out.println("Hash code of '" + str1 + ": " + str1.hashCode());
System.out.println("Hash code of '" + str2 + ": " + str2.hashCode());
}
}
Hash code of 'ABC': 75604983
Hash code of 'BCA': 75604983
Explanation: Even though "ABC" and "BCA" are different strings, they happen to have the same hash code. This is a collision. When using `hashCode()` with collections like `HashSet`, it's essential to remember that you must still use the equals()
method to determine true equality after a collision occurs.
The implementation of hashCode()
is crucial for ensuring efficient behavior in hash-based collections. The contract states that if two objects are equal according to the equals(Object obj)
method, then their hashCode()
values must be the same. Conversely, if two objects have the same hashCode()
value, they may or may not be equal.
Modifying a string's content after it has been added to a hash-based collection will likely break the expected behavior due to changes in its hash code. It is best practice that you don't change strings once added into collections that rely on their hashCode values, for example HashSets.
⬅ Previous Topic
Java StringgetChars()
methodNext Topic ⮕
Java StringindexOf()
methodYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.