Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Java SE 综合讨论区  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
话题被移动
该话题已被移动 - littledeer1974 , 2004-10-29 13:31
如果您尚不清楚该话题被移动的原因,请参考论坛规则以及本版公告或者联系本版版主。
作者 请问关于Map(HashMap)中get()方法的问题.
xinzi





发贴: 12
积分: 10
于 2003-12-11 15:21 user profilesend a private message to usersearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
我的Map中的key是一个类A的对象, 为什么用通过类A的equals方法相等的对象作为key,不能检索到map中的元素? 附源代码.


public class A
{
private int year;
private int month;
private String name;

public A(int year, int month, String name)
{
this.year = year;
this.month = month;
this.name = name;
}
//.....getter setter方法省略

public boolean equals(Object other)
{
if ( !(other instanceof A) ) return false;
A castOther = (A) other;
return this.getYear()==castOther.getYear() && this.getMonth()==castOther.getMonth()
&& this.getName().equals(castOther.getName());
}

public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append(this.getYear()).append(".").append(this.getMonth()).append("--").append(this.getName());
return sb.toString();
}

public static void main(String [] args)
{
Map map = new HashMap();
map.put(new A(2003,12,"aaa"), "Va");
map.put(new A(2003,12,"bbb"), "Vb");
map.put(new A(2003,12,"ccc"), "Vc");
map.put(new A(2003,12,"ddd"), "Vd");
boolean contains = map.containsKey(new A(2003,12,"ddd"));
System.out.println("map=" + map);
A a = new A(2003,12,"bbb");
System.out.println(map.get(a));
System.out.println(contains);

Hashtable ht = new Hashtable();
ht.put(new A(2003,12,"aaa"), "Va");
ht.put(new A(2003,12,"bbb"), "Vb");
ht.put(new A(2003,12,"ccc"), "Vc");
ht.put(new A(2003,12,"ddd"), "Vd");
System.out.println("\nht=" + ht);
System.out.println(ht.get(new A(2003,12,"bbb")));
}
}


运行的结果是:

map={2003.12--ddd=Vd, 2003.12--bbb=Vb, 2003.12--aaa=Va, 2003.12--ccc=Vc}
null
false

ht={2003.12--bbb=Vb, 2003.12--ddd=Vd, 2003.12--aaa=Va, 2003.12--ccc=Vc}
null





话题树型展开
人气 标题 作者 字数 发贴时间
5452 请问关于Map(HashMap)中get()方法的问题. xinzi 1952 2003-12-11 15:21
4685 Re:请问关于Map(HashMap)中get()方法的问题. xinzi 52 2003-12-11 15:55
4383 Re:请问关于Map(HashMap)中get()方法的问题. heaven 54 2003-12-11 16:35
4348 Re:请问关于Map(HashMap)中get()方法的问题. mochow 51 2003-12-11 19:58
4555 Re:请问关于Map(HashMap)中get()方法的问题. xinzi 36 2003-12-12 10:24

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923