* Note that it is generally necessary to override the <tt>hashCode</tt> * method whenever this method is overridden, so as to maintain the * general contract for the <tt>hashCode</tt> method, which states * that equal objects must have equal hash codes. from java.lang.Object src相同的对象必须有相同的hash code
public class Sample { public static void main(String[] args) { String s1="ss"; String s2="ss"; if(s1.equals(s2)){ System.out.println("s1和s2的hashCode是一样的"); }else{ System.out.println("error"); } }
哈希表需要根据hashCode来决定存放对象的位置,以及存放之后的快速查询定位。hashCode不要求唯一
hashmap操作的其实是一个数组。再继续看个简单点的hashmap的get方法 public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
key.hash被用来计算数组的下标
* method whenever this method is overridden, so as to maintain the
* general contract for the <tt>hashCode</tt> method, which states
* that equal objects must have equal hash codes. from java.lang.Object src相同的对象必须有相同的hash code
public static void main(String[] args) {
String s1="ss";
String s2="ss";
if(s1.equals(s2)){
System.out.println("s1和s2的hashCode是一样的");
}else{
System.out.println("error");
}
}
}