日期:2014-05-20  浏览次数:20705 次

HashMap中键值访问对象的问题
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()

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