Junior — Middle
Is it possible to ensure the same hashCode for different String objects and how does it affect collections?
sobes.tech AI
Answer from AI
Yes, in Java, different String objects can have the same hashCode because the hashCode for a String is computed based on its content, not its reference. For example, the string "abc" and a new String with the same content "abc" will have the same hashCode.
This affects hash-based collections like HashMap, HashSet: if two objects have the same hashCode, they go into the same bucket, and then the equals() method is used to check equality. If equals() returns true, the objects are considered equal keys.
Example:
String s1 = "test";
String s2 = new String("test");
System.out.println(s1.hashCode() == s2.hashCode()); // true
System.out.println(s1.equals(s2)); // true
HashSet<String> set = new HashSet<>();
set.add(s1);
System.out.println(set.contains(s2)); // true
Thus, having the same hashCode for different objects with the same content is normal and expected behavior, important for correct operation of hash collections.