import java.util.*;
class Person{
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public int hashCode(){
return this.name.hashCode()+this.age*1000;
}
public boolean equals(Object obj){
Person p = (Person)obj;
if(p.name.equals(this.name)&&p.age==this.age){
return true;
}else{
return false;
}
}
public String toString(){
return "姓名:"+this.name+",年龄:"+this.age;
}
}
public class TestHashCodeAndEquals{
public static void main(String args[]){
Map m = new HashMap();
//m.put("张三",new Person("张三",30));
//System.out.println(m.get("张三"));
//输出:姓名:张三,年龄:30
//覆写hashCode和equals方法之前
//m.put(new Person("张三",30),"张三");
//System.out.println(m.get(new Person("张三",30)));
//输出:null
//Person p = new Person("张三",30);
//m.put(p,"张三");
//System.out.println(m.get(p));
//输出:张三
//覆写hashCode和equals方法之后
m.put(new Person("张三",30),"张三");
System.out.println(m.get(new Person("张三",30)));
//输出:张三
}
}
简单理解:
没覆写之前两次new Person(...,...),对象的hashCode不同,覆写后两次new Person(...,...),对象的hashCode相同。
不知道在内存中是否是一个?测试一下:
Person p1=new Person("张三",30);
Person p2=new Person("张三",30);
System.out.println(p1==p2);
System.out.println(p1.equals(p2));
输出:
false
true
在内存中应该还是两个对象~~之前理解有误额。