返回信息流import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class HashTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<Name> hs = new HashSet<Name>();
hs.add(new Name("zhang","san"));
hs.add(new Name("zhang","san"));
System.out.println(hs.size());
Map<Name,String> map = new HashMap<Name,String>();
map.put(new Name("li","si"), "li1");
map.put(new Name("li","si"), "li2");
String s = map.get(new Name("li","si"));
System.out.println(map.size());
System.out.println(s);
}
}
class Name{
private String first;
private String last;
public Name(String first,String last){
this.first = first;
this.last = last;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public boolean equals(Name other) {
// TODO Auto-generated method stub
if(this==other)
return true;
else if(first.equals(other.getFirst())&&last.equals(other.getLast())){
return true;
}
return false;
}
public int hashCode() {
// TODO Auto-generated method stub
int code = first.hashCode();
System.out.println(code);
return code;
}
}
为什么输出set的size为2,map的size也为2呢?
明明add的两个对象,所对应的hashcode是相同的。set怎么为判断为不同的对象呢?
而且String s = map.get(new Name("li","si"));这个s竟然为null
这是一条镜像帖。来源:北邮人论坛 / java / #22416同步于 2012/5/13
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
关于HashSet
pastore
2012/5/13镜像同步8 回复
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
你在Override equals时有问题了 。正确的声明应该是 public boolean equals(Object other),可以通过添加Annotation (@Override)测试。 你的equals声明在调用add方法时不能被调用。
//修改equlas方法如下
public boolean equals(Object other)
{
// TODO Auto-generated method stub
if (this == other)
{
return true;
}
Name other1 = (Name)other;
if (first.equals(other1.getFirst()) && last.equals(other1.getLast()))
{
return true;
}
return false;
}
懂了,3ks
【 在 linsword20 的大作中提到: 】
: 你在Override equals时有问题了 。正确的声明应该是 public boolean equals(Object other),可以通过添加Annotation (@Override)测试。 你的equals声明在调用add方法时不能被调用。
: //修改equlas方法如下
: public boolean equals(Object other)
: ...................
是equals的问题,equals方法的参数写成(Name object),然后它就不认识了。因为Object的equals方法参数为(Object object)。没有覆盖父类中的方法,所以不会被调用。
【 在 hellotree 的大作中提到: 】
: 我认为跟equals方法没关系,主要是Object的hashCode方法,Name override hashCode的方法。
: 你可以测一下。
【 在 pastore 的大作中提到: 】
: 是equals的问题,equals方法的参数写成(Name object),然后它就不认识了。因为Object的equals方法参数为(Object object)。没有覆盖父类中的方法,所以不会被调用。
equals 会不会调hashCode方法? 应该会。不然怎么判断对象相同呢。
equals不会调用hashCode。只是在HashSet中会先调用hashCode再调用equals。
【 在 hellotree 的大作中提到: 】
:
: equals 会不会调hashCode方法? 应该会。不然怎么判断对象相同呢。