我有一個Class
持有使用自它的對象引用忽略equals對於自參照親子對象
public class MyObject {
private String name;
private List<MyObject> childrens;
private MyObject parent;
@Override
public int hashCode() {
int hash = 5;
hash = 13 * hash + Objects.hashCode(this.name);
hash = 13 * hash + Objects.hashCode(this.childrens);
hash = 13 * hash + Objects.hashCode(this.parent);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MyObject other = (MyObject) obj;
if(!this.name.equalsIgnoreCase(other.name))
return false;
if(this.parent==null)
{
if(other.parent!=null)
{
return false;
}
}else if(!this.parent.equals(other.parent))
{
return false;
}
if(!allChildrenEqual(this,other))
{
return false;
}
return true;
}
private boolean allChildrenEqual(MyObject aThis, MyObject other) {
List<MyObject> children1=aThis.getChildrens();
List<MyObject> children2=other.getChildrens();
//Avoid infinite recusion can't use anything simple as
// list1 equals other list
return true;
}
我想知道我怎麼能覆蓋中父子關係等於正常與之相比的層次這些對象沒有進入無限遞歸併導致StackOverflowError。
我有一種感覺,我失去了一些真正明顯的東西。 在此先感謝。
父母總是非空(對於頂部元素?)。否則,你的代碼在檢查孩子之前會返回false或者拋出NPE。 – Codebender
@Codebender對不起,我的錯誤錯過了代碼片段中的條件。編輯它 –
如果您使用'equalsIgnoreCase'來比較名稱,那麼您需要'name'字段的散列也不區分大小寫,否則您的破解散列實現。 – khelwood