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了

解决方案 »

  1.   

    put的时候和get的时候都调用了 
      

  2.   

    map.put(new Person("Ls",25),"A"); 
    map.get(new Person("Ls",25));LZ将Person对象做为map的KEY,
    要知道map中的KEY是不能重复的,所以map在put()和get()时要判断KEY是否重复,
    判断就要用到做为KEY的Person类中的hashCode()和equals()方法。这部分调用JDK的JAR包都做好了,有兴趣可以查JDK源码。
      

  3.   

    应为hashmap在get是就要去查询键值,如果你不重写那个两个方法,new Person("Ls",25)对象和你在map里面new Person("Ls",25)肯定不是同是对象