Xav*_*aan 5 java duplicates hashset
这个问题肯定不是新问题,但我在任何地方都找不到任何有用的答案.
正如您在下面的代码中看到的那样,equals和hashcode方法被覆盖,但它仍然允许重复.Hashcode由Netbeans自动生成.
@Override
public boolean equals(Object o)
{
TaskDetails other = (TaskDetails) o;
if ( (id_subtask == other.id_subtask)
&& ((date.compareTo(other.date)) == 0) )
{
System.err.println("Duplicate Entry"+id_subtask+" + "+other.id_subtask);
return true;
}
else
{
System.out.println("Good!" +id_subtask+" + "+other.id_subtask);
return false;
}
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + this.id_subtask;
hash = 71 * hash + this.id_team_member;
hash = 71 * hash + Float.floatToIntBits(this.nb_hours);
hash = 71 * hash + (this.date != null ? this.date.hashCode() : 0);
hash = 71 * hash + (this.comment != null ? this.comment.hashCode() : 0);
hash = 71 * hash + (this.subtask_name != null ? this.subtask_name.hashCode() : 0);
System.out.println("Hash : "+hash + "Subtask : " + id_subtask);
return hash;
}
Run Code Online (Sandbox Code Playgroud)
这个代码用于在hashset中添加一个条目:
TaskDetails newTaskDetails = new TaskDetails
(
s.getId_subtask(),
mus.teamMember.getId_team_member(),
f,
mysqlFormat.format(caldate),
c.substring(0, Math.min(c.length(), 100)),
s.getName_subtask()
);
allTasks.add(newTaskDetails);
Run Code Online (Sandbox Code Playgroud)
(allTasks是Hashset)
此代码用于函数A和B.
如果只执行功能A,它可以正常工作.如果在函数A之后执行函数B(所以上面的代码执行两次),那么即使触发了system.err说有重复的条目,hashset突然接受重复项?
代码中是否存在缺陷,或者我只是遗漏了什么?
谢谢您的帮助!
您使用2个字段将2个对象视为"相等",但您使用的字段数超过2个来构造哈希码.你的hashCode()方法不能比你的equals()方法更具体.作为一个好的经验法则,您的hashCode()方法不应该使用您的方法不使用的任何字段equals()(但它可以使用更少的字段).更具技术性,如果2个对象"相等",它们必须具有相同的哈希码(反之则不需要).
| 归档时间: |
|
| 查看次数: |
5759 次 |
| 最近记录: |