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()
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()
解决方案 »
- socket 异常
- 再问个正则..谢谢先
- 关于对象是否为空的判断(很奇怪)
- 各位大虾来帮忙啊!麻烦了
- 问题:who有JavaScript Reference的编程资料?
- 编程进行中文转换是出现了UnsupportedEncodingException编译错误,怎么解决?
- 在new一个java对象时,如何控制程序员是否必须实现一个方法
- 我想考高级程序员,大家给点建议!!!大家直言不讳啊!
- resin的配置
- 如何在窗口的标题栏显示数据库的账号(账号已好的,怎样添加)
- db2 修改某列的数据 规则:把某列2字开头数据的替换为1,在线等帮助
- 各位朋友,问个java读取google网页内容的问题,请进来看
Element test=new Element(5);
查询的时候用变量名
if(h2.containsKey(test))错误是因为两次内容相同但地址不同...
每个对象的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;
}
}
比较键值的内容时,确实要重写Object中的hashCode()和equals()方法,我已经解决了。不过还是谢了楼上的回答。
HashMap<Integer, B> mm = new HashMap<Integer, B>();