Given that there are an infinite number of different strings its just not possible to allocate a different int (32bits which can represent up to 4 billion) number for each.
With just 8 characters tehre are 2^60 different strings. This is infinitely larger than
2^32. Naturally the hashcode of some of these strings must clash.
Two objects with the same hashcode do not have to be equal. To know for sure use the equals method. This is basically the strategy used by a hashmap to determine if keys are equal.
Map.get(String key)
- Calculate hashcode of key
- Use modulo to figure out which bucket key belongs too.
- Loop thru all the entries from that bucket attempting to find a matching key.
- When a key match is found return that entries' value.
As a side note as maps gain more and more elements it will recreate more buckets and place all the old entries into the new buckets. This helps present the bucket entry list from growing into really really long lists. A map wants many buckets with short lists.
The javadoc for Object.hashcode makes for interesting reading - ive pasted a snippet below.
The equals method implements an equivalence relation:
* It is reflexive: for any reference value x, x.equals(x) should return true.
* It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
* It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
* It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
* For any non-null reference value x, x.equals(null) should return false.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).