当HashSet存储对象时需重新对象对应的类中的equals()方法和hashCode()方法。
package collection;
import java.util.HashSet;
import java.util.Set;
public class TestHashSet {
public static void main(String[] args) {
Set<Name> set=new HashSet<Name>();
set.add(new Name("abc", "123"));
System.out.println(set.contains(new Name("abc", "456")));//结果为true
set.add(new Name("abc", "456"));
System.out.println(set.size());//结果为1
}
}
class Name{
private String first;
private String last;
public Name(String first, String last) {
super();
this.first = first;
this.last = last;
}
/*
* (non-Javadoc)假设以first字段作为两个对象的相等的条件
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this==obj) {
return true;
}
if (obj.getClass()==Name.class) {
Name name = (Name) obj;
return name.first.equals(first);
}
return false;
}
/*
* (non-Javadoc)hashCode统一返回first的hashCode
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return first.hashCode();
}
}
本文通过一个具体示例展示了如何在Java中为自定义类重写equals()和hashCode()方法以确保HashSet能正确存储和检索对象。特别强调了当对象的部分属性相同即认为对象相等的情况下的实现方式。
1041

被折叠的 条评论
为什么被折叠?



