实际上在工作的过程中,我很少会去重写equals这个方法,因为实际应用很少,但是一旦有这样的需求,那么就应该遵守约定。 自反性、一致性、传递性等等。 具体的约定这里我们不多做赘述,我们说一下实际开发中,如果需要重写实现equals方法的诀窍 1、使用==操作符来检查“参数是否为这个对象引用”。 2、使用instanceof操作符来检查“参数是否为正常的类型”。 3、把参数转换成正确的类型。 4、对于该类中的每个关键域,检查参数中的域是否与该对象中对应的。 5、覆盖equals时总要覆盖hashcode。 6、不要企图让equals方法过于智能。 7、不要将equals声明中的Object对象替换为其他的类型。
这个是Object.hashcode的通用约定,如果违反,会导致该类无法结合所有基于散列的集合一起正常工作。 关于equals和hashcode总会遇到面试和笔试的题目,主要集中的知识点在于; 1、如果两个对象equals方法比较是相等的,那么任意一个对象的hashcode方法返回的结果也是相等的。 2、如果两个对象equals方法比较是不相等的,那么任意一个对象的hashcode方法返回的结果不一定相等的。 3、尽量保证让不同的对象拥有不同的散列码(hashcode方法得到的值)。
下面根据几个示例说明。
public static void main(String[] args) { String[] array1 = {"1","2","3"}; String[] array2 = {"1","2","3"}; System.out.println(array1.equals(array2));// 没有重写equals方法,继承了object方法 System.out.println(Arrays.equals(array1,array2));// 重写了equals方法 String str1 = new String("1"); String str2 = new String("1"); System.out.println(str1.equals(str2)); System.out.println(str1==str2); }结果
false true true false接下来看另外的一个例子,关于重写equals方法不重写hashcode的后果
package com.effective.java; public class Pepole { private String name; private String sex; private float stature; private int age; public Pepole(String name, String sex, float stature, int age) { super(); this.name = name; this.sex = sex; this.stature = stature; this.age = age; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Pepole)) { return false; } Pepole p = (Pepole) obj; return this.getName().equals(p.getName()) && this.getSex().equals(p.getSex()) && this.getStature() == p.getStature() && this.getAge() == p.getAge(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public float getStature() { return stature; } public void setStature(float stature) { this.stature = stature; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Pepole [name=" + name + ", sex=" + sex + ", stature=" + stature + ", age=" + age + "]"; } } package com.effective.java; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Test { public static void main(String[] args) { Map<Pepole, String> map = new HashMap<Pepole, String>(); map.put(new Pepole("upxiaofeng", "male", 1.72f, 30), "upxiaofeng"); Set<Entry<Pepole, String>> sets = map.entrySet(); for (Entry<Pepole, String> entry : sets) { System.out.println("Pepole info:"+entry.getKey().toString()+",Pepole Name:"+entry.getValue()); } System.out.println(map.get(new Pepole("upxiaofeng", "male", 1.72f, 30))); } }结果:
Pepole info:Pepole [name=upxiaofeng, sex=male, stature=1.72, age=30],Pepole Name:upxiaofeng null原因是由于没有重写HashCode,put方法把人这个对象放在一个散列桶里面,get方法却在另外一个散列桶中查找。 修正这个问题很简单,只需要在Pepole类提供一个HashCode方法即可。
@Override public int hashCode() { return 1; }结果:
Pepole info:Pepole [name=upxiaofeng, sex=male, stature=1.72, age=30],Pepole Name:upxiaofeng upxiaofeng得到了我们想要的结果。但是产生了一个新的问题,每一个Pepole对象产生的hashcode是相同的,每个对象都被映射到同一个散列桶中,使得散列桶退化为链表了。很大的降低了效率,甚至影响是否能够正常工作。 所以【尽量保证不同的对象拥有不同的散列码】。改进hashcode方法:
@Override public int hashCode() { int result=17; result = 31*result+name.hashCode(); result = 31*result+sex.hashCode(); result = 31*result+Float.floatToIntBits(stature); result = 31*result+age; return result; }对于这两条的实践,出现了两个问题,还是值得注意。 1、使用TreeMap 当使用put方法放入元素的时候会报一下异常
Map<Pepole, String> treemap = new TreeMap<Pepole, String>(); treemap.put(new Pepole("upxiaofeng", "male", 1.72f, 30), "upxiaofeng"); Exception in thread "main" java.lang.ClassCastException: com.effective.java.Pepole cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1290) at java.util.TreeMap.put(TreeMap.java:538) at com.effective.java.Test.main(Test.java:12)原因是Pepole类并没有实现comparable接口,TreeMap是基于红黑树算法实现,是有序的。 2、使用HashMap 使用get(key)方法去获取值得时候,实际上是会调用key这个对象的equals和hashcode方法来比对。