简体   繁体   English

通用n元树中的等于方法

[英]Equals method in a generic n-ary tree

I have this n-ary tree implementation, where each tree class stores the data and it's children in an array. 我有此n元树实现,其中每个树类将数据及其子级存储在数组中。

Also there is my incomplete method equals() . 还有我不完整的方法equals()

public class ArrayNTree<T extends Comparable<T>> implements NTree<T>, Cloneable {

/* Data of the tree*/
private T data;

/* Primary array to store the children */
private ArrayNTree<T>[] children;

...

public boolean equals(Object other) { // FIXME

    if (this == other)
        return true;

    if (other == null)
        return false;

    if(other instanceof ArrayNTree)
        return sameTree( (ArrayNTree<T>) other );

    return false;
}

private boolean sameTree(ArrayNTree<T> xpto) {
    return (this.data == xpto.data &&
            //this.children == xpto.children && ???????
            this.size == xpto.size);
}

My main doubt is how do I go through every child and compare with the other tree since this is an array I think it makes the job a little harder 我主要的疑问是我该如何遍历每个孩子并与另一棵树进行比较,因为这是一个数组,我认为这会使工作更加困难

First, if data or size is different return false 首先,如果datasize不同,则返回false

Then, check its children 然后,检查它的children


  1. one by one: 逐一:

     private boolean sameTree(ArrayNTree<T> xpto) { if(this.data != xpto.data || this.size != xpto.size) return false; for(int i = 0; i<this.children.length: i++){ if(!this.children[i].equals(xpto.children[i])) return false; } return true; } 
  2. Using Arrays.deepEquals() 使用Arrays.deepEquals()

     private boolean sameTree(ArrayNTree<T> xpto) { return this.data == xpto.data && this.size != xpto.size && Arrays.deepEquals(this.children, xpto.equals); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM