import java.util.*;     
public class Exp2 
{    
     public static void main(String[] args){    
          HashMap<Element, Figureout> h2=new HashMap<Element, Figureout>();    
          for(int i=0;i<5;i++)    
               h2.put(new Element(i), new Figureout());    
          System.out.println("h2:");    
          System.out.println("Get the result for Element:");    
          Element test=new Element(5);    
          if(h2.containsKey(test))    
               System.out.println((Figureout)h2.get(test));    
          else   
               System.out.println("Not found");    
     }    

class Element
{    
  int number;    
  public Element(int n)
  {    
     number=n;    
   }     
 }
class Figureout
{    
     Random r=new Random();    
     boolean possible=r.nextDouble()>0.5;    
     public String toString()
     {    
          if(possible)    
               return "OK!";    
          else   
               return "Impossible!";    
     }    
}   
上面的程序是创建HashMap 输出键值是 Element test=new Element(5)对应的对象new Figureout(),这儿 if(h2.containsKey(test))  判断是错误的,也就是没有找到相等的
 键值,这是为什么。怎样才能使if条件成立,执行toString()

解决方案 »

  1.   

    在加入map前就这样写:
    Element test=new Element(5);   
    查询的时候用变量名
    if(h2.containsKey(test))错误是因为两次内容相同但地址不同...
      

  2.   

    地址不一样;
    每个对象的Hashcode()好像就是取其地址吧。。 HashMap<Integer, B> mm = new HashMap<Integer, B>();
    int code = new A("k").hashCode();
    mm.put(code, new B("kk"));
    if(mm.containsKey(code)){
    System.out.println("true");
    }else{
    System.out.println("false");
    }
    class A{
    String a = null;
    public A(String a){
    this.a = a;
    }
    }
    class B{
    String b = null;
    public B(String b){
    this.b = b;
    }
    }
      

  3.   

    你用类对象做键值,好像要重写该类的hashCode()和equals()方法吧
      

  4.   

    Xia5523回复中mm.put(code, new B("kk")),不能直接把int型的hashcode值放入到hashmap中,
    比较键值的内容时,确实要重写Object中的hashCode()和equals()方法,我已经解决了。不过还是谢了楼上的回答。
      

  5.   

    int类型确实不行啊,但是那个参数类型用Integer的话,就行了啊
    HashMap<Integer, B> mm = new HashMap<Integer, B>();