鉴于有无限数量的不同字符,不可能为每个字符分配一个不同的int(32位可以表示高达40亿)编号。
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.
具有相同哈希码的两个对象不一定相等。要确定,请使用equals方法。这基本上是hashmap用来确定键是否相等的策略。
地图获取(字符串键)
- 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.
附带说明,随着地图增加更多元素,它将重新创建更多存储区,并将所有旧条目放入新存储区。这有助于避免桶条目列表变得非常长。地图需要许多桶和短列表。
Object.hashcode的Javadoc很有意思-我粘贴了一小段。
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.
Object类的equals方法实现了最具有区分能力的对象等同关系;也就是说,对于任何引用值x和y,当且仅当x和y引用同一对象时(x==y的值为true),该方法返回true。