关于重写equals()和hashCode()的疑问
Person——>String映射
import java.util.Map;
import java.util.HashMap;
class Person{
private String name;
private int age;
public Person(String name,int age){ //构造
this.name = name ;
this.age =age ;
}
public String toString(){
return "姓名:"+this.name+",年龄:"+this.age ;
}
}
public class HashMapDemo{
public static void main(String[] args){
Map<Person,String> map= new HashMap<Person,String>(); //实例化map对象
map.put(new Person("Ls",25),"A"); //增加内容
System.out.println(map.get(new Person("Ls",25))); //查找内容
}
}
程序运行结果:null
当Person类重写equals()和hashCode()方法后,主方法没有变
public boolean equals(Object obj){ //重写
if(this == obj){ //判断地址是否相同
return true;
}
if(!(obj instanceof Person)){ //判断是否是Person的实例
return false;
}
Person per = (Person)obj; //向下转型
if(this.name.equals(per.name)&&this.age == per.age){
return true;
}else{
return false;
}
}
public int hashCode(){ //重写
return this.name.hashCode()*this.age;
}
程序运行结果:A
问题是我重写的这两个方法,但并没有调用啊 怎么就能通过new Person("Ls",25) 找到A了