我正在经历一种奇怪的行为,我不知道为什么。我试图从LinkedHashSet中删除一个元素,但它没有被删除。
我的类文档定义了:
protected Set<Author> authors = new LinkedHashSet<>();当id和role都相等时,Author等于:
@Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + Objects.hashCode(this.id);
hash = 53 * hash + Objects.hashCode(this.role);
System.out.println("Calling hashcode: " + hash);
return hash;
}
@Override
public boolean equals(Object obj) {
System.out.println("Calling equals");
if (obj == null) {
return false;
}
System.out.println("1");
if (getClass() != obj.getClass()) {
return false;
}
System.out.println("2");
final Author other = (Author) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
System.out.println("3");
if (!Objects.equals(this.role, other.role)) {
return false;
}
System.out.println("4");
return true;
}然后,使用某些调试打印删除的代码:
public void removeAuthor(Author author) {
System.out.println(">removeAuthor [" + author.hashCode() + "]: " + author);
if (document.getAuthors() != null) {
System.out.println("[" + document.getAuthors().size() + "] Authors BEFORE:");
document.getAuthors().forEach((pp) -> {
System.out.println("[" + pp.hashCode() + "] " + pp);
});
}
if (document != null) {
if (document.getAuthors() != null) {
document.getAuthors().remove(author);
}
}
if (document.getAuthors() != null) {
System.out.println("[" + document.getAuthors().size() + "] Authors AFTER:");
document.getAuthors().forEach((pp) -> {
System.out.println("[" + pp.hashCode() + "] " + pp);
});
}
}这将打印以下内容(我补充一下我的评论):
// Call to hashCode() to print the author that will be removed
Calling hashcode: 400605768
// Author that will be removed
>removeAuthor [400605768]: Author{id=self, name=Self Centre, forename=null, familyName=null, role=Writer}
// List before calling remove, it gives 2 authors
[2] Authors BEFORE:
Calling hashcode: -1820871746
[-1820871746] Author{id=self, name=Self Centre, forename=null, familyName=null, role=Researcher}
Calling hashcode: 400605768
[400605768] Author{id=self, name=Self Centre, forename=null, familyName=null, role=Writer}
// This hashCode call is probably done by remove(). As it can be seen, the object to be removed *is* on the Set
Calling hashcode: 400605768
// List after calling remove, it gives again 2 authors
[2] Authors AFTER:
Calling hashcode: -1820871746
[-1820871746] Author{id=self, name=Self Centre, forename=null, familyName=null, role=Researcher}
Calling hashcode: 400605768
[400605768] Author{id=self, name=Self Centre, forename=null, familyName=null, role=Writer}
Calling hashcode: -1820871746我习惯于一般地使用套装。这可能是个愚蠢的错误,但我找不到它在哪里。此外,compareTo或其他方法似乎不用于测试等式。
发布于 2017-03-19 22:11:17
我想我已经解决了这个迷雾,多亏了调试。这是Ajax使用中的一个明显错误。创建LinkedHashSet时,元素将根据其hashCode添加到索引中的哈希表中。有时候,Ajax JSF操作可以改变内存中对象的role,这使它们改变了它们的散列。但是,--哈希表中最初插入它们的位置--在所有上都没有更改!因此,您现在有了一个具有要删除的特定散列的元素,该元素确实存在于您的集合中(如所见,散列是相同的),但是当实际代码试图从table[ (table.length-1) & hash ]中删除元素时,将永远找不到它,因为它不在该位置--它最初是用另一个哈希值添加的。这解决了错误,这是完全合乎逻辑的。
https://stackoverflow.com/questions/42857489
复制相似问题