String HashCode Collision Aa BB
Aa and BB share hashCode 2112 yet stay two entries in a HashMap, showing why equals must back every hash-based lookup.
Code
import java.util.HashMap;
import java.util.Map;
public class StringHashCodeCollision {
public static void main(String[] args) {
// "Aa" 与 "BB" 的 hashCode 都是 2112:内容不同、哈希相同
String first = "Aa";
String second = "BB";
System.out.println("hash Aa = " + first.hashCode());
System.out.println("hash BB = " + second.hashCode());
// 哈希桶相同不等于对象相等:HashMap 里仍是两个独立条目
Map<String, String> values = new HashMap<>();
values.put(first, "alpha");
values.put(second, "beta");
System.out.println("size = " + values.size());
System.out.println("get Aa = " + values.get("Aa"));
System.out.println("get BB = " + values.get("BB"));
System.out.println("equals = " + first.equals(second));
}
}How it works
String HashCode Collision Aa BB keeps everything in the class StringHashCodeCollision and the function main.
What to watch for
- The import surface (if any) is all standard library, all versioned with the language itself.
Using it
Look for the hash Aa =, hash BB =, size = prefixes when the file runs; they tie each line to its step.
Key statements
Map<String, String> values = new HashMap<>();
values.put(first, "alpha");
values.put(second, "beta");
Interactive Tools for This Topic
FAQ
- What does String HashCode Collision Aa BB print when run?
- Invoke the file as-is — the `hash Aa =`, `hash BB =`, `size =` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.