hashCode不是根据对象内容来产生一个值的么?不是,是根据方法是如何运算的,
下面是示例代码可以长了点,拷到机上慢慢看吧
package test1;
/**
* 因为map的存储原理与hashset的是一样的,写了不同三个类来测方式结果
* Person1 没复写hashCode和equals方法
* Person2 复写hashCode和equals方法,hashcode方法返回结果固定不变
* Person3 复写hashCode和equals方法,
*/
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class HashMapTest {
public static void main(String[] args) {
Collection set1 = new HashSet();
set1.add(new Person1("zhang",23));
set1.add(new Person1("zhang",23));
set1.add(new Person1("zhang",23));
System.out.println("set1:"+set1.size());
Collection set2 = new HashSet();
set2.add(new Person2("zhang",23));
set2.add(new Person2("zhang",23));
set2.add(new Person2("zhang",23));
System.out.println("set2:"+set2.size());
Collection set3 = new HashSet();
set3.add(new Person3("zhang",23));
set3.add(new Person3("zhang",23));
set3.add(new Person3("zhang",23));
System.out.println("set3:"+set3.size());
}
}
//该类不复写从Object继承来hashcode方法和equals方法,所以两个对象的hashcode不可以相同
class Person1{
private String name;
private int age;
public Person1(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
//该类复写从Object继承来hashcode方法和equals方法,但把返回的hashcode值固定,也就是说此类对象的返回hashcode值相同
class Person2{
private String name;
private int age;
public Person2(String name, int age) {
super();
this.name = name;
this.age = age;
}
//复写hashCode();因为这个返值相同,还不能确定是否是同一个对象,所每次都会执行equals方法
@Override
public int hashCode() {
return 60;
}
//复写equals方法
@Override
public boolean equals(Object obj) {
System.out.println("Persen2的equals执行了");//测试每次操作是否都执行到这
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person2 other = (Person2) 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;
}
}
/**
* 该类复写从Object继承来hashcode方法和equals方法
* 类的成员变量(name和age)都参与这两个方法的返回结果的运算
*/
class Person3{
private String name;
private int age;
public Person3(String name, int age) {
super();
this.name = name;
this.age = age;
}
//复写hashCode(),如果两个对象的name 和age都相等,则返回结果相同,这时会执行equals方法,否则认为是两个不同的对象,不会再执行equals方法
@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;
}
//复写equals方法,当则行到这,表明hashcode()返值相同,
@Override
public boolean equals(Object obj) {
System.out.println("Persen3的equals执行了");//测试什么时候执行到这
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person3 other = (Person3) 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;
}
}
|