Set s=new HashSet();
s.add(new Person( "name ", "age "));
System.out.println(s.contains(new Person( "name ", "age ")));
竟然是false ,高手解释下吧
------解决方案--------------------
Set中的contains方法会调用对象的equals方法来比较两个对象是否相同.
Object.equals方法还和hashCode方法相关
所以你需要做的就是让Person类重载这两个方法.
如果想方便的话可以用jarkata的common-lang包.
http://www.juixe.com/techknow/index.php/2007/02/01/jakarta-commons-lang-builders/
public boolean equals(Object obj) {
if (obj instanceof Person == false) {
// Not even the same class
return false;
}
if (this == obj) {
// The same object reference
return true;
}
Person rhs = (Person)obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(name, rhs.name)
.append(age, rhs.age)
.isEquals();
}
public int hashCode() {
// Pick a hard-coded, randomly chosen, non-zero,
// odd number ideally different for each class
return new HashCodeBuilder(17, 37)
.append(name)
.append(age)
.toHashCode();
}