Topic: 请问关于Map(HashMap)中get()方法的问题.

  Print this page

1.请问关于Map(HashMap)中get()方法的问题. Copy to clipboard
Posted by: xinzi
Posted on: 2003-12-11 15:21

我的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


2.Re:请问关于Map(HashMap)中get()方法的问题. [Re: xinzi] Copy to clipboard
Posted by: xinzi
Posted on: 2003-12-11 15:55

为什么用String类作为key就可以检索到,而我自己的类作key就不行?还需要作什么吗?请大家指教啊!

3.Re:请问关于Map(HashMap)中get()方法的问题. [Re: xinzi] Copy to clipboard
Posted by: heaven
Posted on: 2003-12-11 16:35

重载equals的时候一定要重载hashcode,确保equals为真的两个对象具有相同的hashcode。

4.Re:请问关于Map(HashMap)中get()方法的问题. [Re: xinzi] Copy to clipboard
Posted by: mochow
Posted on: 2003-12-11 19:58

楼上说得很对。
要想详细了解的话,看看Effective java吧
里面有个item讲的很详细。

5.Re:请问关于Map(HashMap)中get()方法的问题. [Re: xinzi] Copy to clipboard
Posted by: xinzi
Posted on: 2003-12-12 10:24

谢谢楼上两位

通过重载hashCode方法,确实把那个问题解决了!


   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