假设您有一个类,并创建了一个HashSet来存储此类的实例。如果尝试添加相等的实例,则集合中仅保留一个实例,这很好。
但是,如果HashSet中有两个不同的实例,并采用一个实例并使其与另一个实例完全相同(通过复制字段),则HashSet将包含两个重复的实例。
这是演示此代码的代码:
public static void main(String[] args)
{
HashSet set = new HashSet<>();
GraphEdge edge1 = new GraphEdge(1, "a");
GraphEdge edge2 = new GraphEdge(2, "b");
GraphEdge edge3 = new GraphEdge(3, "c");
set.add(edge1);
set.add(edge2);
set.add(edge3);
edge2.setId(1);
edge2.setName("a");
for(GraphEdge edge: set)
{
System.out.println(edge.toString());
}
if(edge2.equals(edge1))
{
System.out.println("Equals");
}
else
{
System.out.println("Not Equals");
}
}
public class GraphEdge
{
private int id;
private String name;
//Constructor ...
//Getters & Setters...
public int hashCode()
{
int hash = 7;
hash = 47 * hash + this.id;
hash = 47 * hash + Objects.hashCode(this.name);
return hash;
}
public boolean equals(Object o)
{
if(o == this)
{
return true;
}
if(o instanceof GraphEdge)
{
GraphEdge anotherGraphEdge = (GraphEdge) o;
if(anotherGraphEdge.getId() == this.id && anotherGraphEdge.getName().equals(this.name))
{
return true;
}
}
return false;
}
}
上面代码的输出:
1 a
1 a
3 c
Equals
有没有一种方法可以强制HashSet验证其内容,以便删除在上述情况下创建的可能重复条目?
一种可能的解决方案是创建一个新的HashSet并将内容从一个哈希集复制到另一个哈希集,以使新哈希集不包含重复项,但是我不喜欢这种解决方案。