hashcode方法解析
- 为什么要有hashcode
总结:如果一个对象 不往 与hash有关的集合中放 那么hashcode()方法 写不写无所谓, 否则必须写hashcode方法 ,hashcode能加快比较的速度 ,
public V put(K key, V value) { // hashmap的put方法
return putVal(hash(key), key, value, false, true);
}
equals 相等 hashcode 必须相等 hashcode不相等 equals 必不相等
这样 在往hash有关的集合中放数据 只要拿到hash 就能快速判断是否往集合中放
- hashcode 能不能返回一个随机值
java 的hashcode 方法是不能返回一个随机数
以String 字符串举例子
String a="123";
String b=new String("123");
a.equals(b) // true
equals 相等的两个对象 hash值必定相等 所以hashcode 不能返回一个随机数 这也是String对象重写hashcode 的原因
public boolean equals(Object obj) { // 在object方法中 equals 方法判断的饿也是 对象的地址
return (this == obj);
}