hashCode()方法和equals方法的重要性。

时间:2023-03-09 15:02:46
hashCode()方法和equals方法的重要性。

在Object中有两个重要的方法:hashCode()和equals(Object obj)方法,并且当你按ctrl+alt+s时会有Generator hashCode()和equals()。我们不禁会想这两个方法到底有什么用,让eclipse提供自动生成这两个方法的模板呢?

这两个方法主要是在hash的数据结构中。如HashSet<E> 、 HashMap<K,V>中。

内容提要:

下面的代码ElementWithoutHashAndEqual类中定义了字段、构造方法、把hashCode()和equals()方法注释掉。然后再HashTest这个类中进行测试,看看运行结果。然后你再把ElementWithoutHashAndEqual类中的hashCode()和equals()方法的注释去掉,你

再看看运行结果是什么。这时你就会发现hashCode()和equals()方法的重要性了。 接着再从源码的角度看看为什么需要些这两个方法.

//ElementWithoutHashAndEqual类的代码如下:

 package com.qls.hashAndEquals;

 public class ElementWithoutHashAndEqual {
private int age;
private String name; public ElementWithoutHashAndEqual(int age, String name) {
this.age = age;
this.name = name;
} /*@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ElementWithoutHashAndEqual other = (ElementWithoutHashAndEqual) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}*/ public String toString() {
return "ElementWithoutHashAndEqual [age=" + age + ", name=" + name + "]";
}
public static void main(String[] args) {
// TODO Auto-generated method stub } }

//HashTest的代码如下:

 package com.qls.hashAndEquals;

 import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.HashSet; /**在HashSet<E>,HashMap<K,V>中的元素E和K,必须要重写hashCode()和equals方法。
* 在大多数情况下E 写成String,Integer
* 等java自带的类。其实这些类已经重写了Object类中hashCode()和equals方法。
* 所以你感觉不到hashCode()方法和equals()方法的重要性。
* 这里我们自定义一个类,看它不重写hashCode()和equals方法会有什么后果。
* @author 秦林森
*
*/
public class HashTest { public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
// TODO Auto-generated method stub
/**
* 用HashSet做例子看HashSet<E>中的元素E类中不重写hashCode()方法,和equals(Object obj);方法
* 的效果:
* 下面HashSet的遍历结果为:
* ElementWithoutHashAndEqual [age=18, name=sixi]
ElementWithoutHashAndEqual [age=18, name=sixi]
ElementWithoutHashAndEqual [age=18, name=sixi]
咋看以下是不是感觉这违背了HashSet不能加重复元素的基本原则。
其实这并没有违背因为Object类中的equals方法是比较两个对象的地址的。
那么hashCode()为什么要重写呢?
再看一看HashMap做例子的情况吧!
*/
HashSet<ElementWithoutHashAndEqual> hashSet = new HashSet<ElementWithoutHashAndEqual>();
hashSet.add(new ElementWithoutHashAndEqual(18, "sixi"));
hashSet.add(new ElementWithoutHashAndEqual(18, "sixi"));
hashSet.add(new ElementWithoutHashAndEqual(18, "sixi"));
for(ElementWithoutHashAndEqual e2:hashSet){
System.out.println(e2);
}
/**
* HashMap做例子看看HashMap<K,V>中的元素K这个类不重写hashCode()和equals方法的严重性。
*/
HashMap<ElementWithoutHashAndEqual, Integer> hashMap=new HashMap<>();
//先用反射向HashMap中添加元素:
hashMap.put(ElementWithoutHashAndEqual.class
.getConstructor(new Class[]{int.class,String.class})
.newInstance(new Object[]{29,"ouyangfeng"})
, 1);
//我们再看看用get(K key)方法能不能把value取出来。
Integer value = hashMap.get(ElementWithoutHashAndEqual.class
.getConstructor(new Class[]{int.class,String.class})
.newInstance(new Object[]{29,"ouyangfeng"}));
System.out.println("value="+value);//输出结果为value=null,而不是value=1.
/**
* 直接new一个对象加在HashMap中。这时你就会看得非常明白了,我之所以用反射创建对象,
* 因为这种创建对象方式比较不容易看懂,从而迷惑你以为put(key,value) 和get(key)中的key是
* 同一个对象。
*/
hashMap.put(new ElementWithoutHashAndEqual(6, "AbrahamLincoln"), 3);
//下面语句的输出结果还为value=null.
System.out.println("value="+hashMap.get(new ElementWithoutHashAndEqual(6, "AbrahamLincoln")));
/**
* 但是当你把ElementWithoutHashAndEqual这个类中的hashCode()、equals()方法的注释取消时,
* 输出结果就会变为你所想要的结果了,结果如下:
* ElementWithoutHashAndEqual [age=18, name=sixi]
value=1
value=3
生成hasCode和equals方法如下:
ctr+alt+s---->Generate hashCode() and equals()。便可以生成这两个函数了。
下面将出源码中看为什么需要在HashSet<E> 和HashMap<K,V>中的E、 K需要这两个函数。
*/
} }

分析为什么需要hashCode()和equals()方法。分析如下:

首先讲在HashMap中如何根据key,得到value的。

第一步:int hash=hash(key)【这个函数调用了key类中的hashCode()函数】得到某个值,

第二步:根据函数int i=indexFor(hash,table.length);找到这个i值在数组table的值table[i],这个table[i]中的值就是Map.Entry<K,V>【其中Entry<K,V> 为Map中的一个静态类】

第三步:有可能多个对象产生的hashCode()值一样,所以在源码中进行了这样的遍历:

for (Entry<K,V> e = table[i]; e != null; e = e.next) {//这个遍历意思就是table[i]中所存放的值Entry<K,V>可能不止一个。用到了链表的数据结构,对各个节点进行遍历。
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))//对Entry<K,V>进行筛选,找到符合的Entry<K,V>,这个必然只有一个。

第四步:用Entry<K,V>中的getValue(),便可以取得value值了。上述步骤所用到的源码如下所示:

  final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
} int hash = (key == null) ? 0 : hash(key);
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 != null && key.equals(k))))
return e;
}
return null;
}
 public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue();
}

在HashSet 中其实它添加元素也用到了Map中的方法,源码如下所示:

public boolean add(E e) {
return map.put(e, PRESENT)==null;
}。