1

我正在研究多项式计算器。我的问题是equals方法。以下是相关代码:

public class Poly{
    Term[] terms;

    //Constructors-------------------------------------------
    public Poly() {}
    public Poly(ArrayList<Term> Terms) {
        terms = Terms.toArray(new Term[Terms.size()]);
        Arrays.sort(terms, new TermComparator());
    }

    //Methods-------------------------------------------------
    public boolean equals(Poly x) {
        boolean q=false;
        if(this == x){
            q=true;
        }
    return q;
    }

    //used in constructor to order terms
    class TermComparator implements Comparator<Term> {
        @Override
        public int compare(Term t1, Term t2) {
            return t2.getExp() - t1.getExp();
        }
    }
}

即使两个 Poly 对象具有相同的值,equals 方法也始终返回 false。有人可以帮忙吗?

4

3 回答 3

5

您的 Poly 类 equals 方法应如下所示

@Override
public boolean equals(Object obj) {
    if (this == obj) //checking both are same instance
        return true;
    if (obj == null) // checking obj should not be null
        return false;
    if (getClass() != obj.getClass()) //checking both objects from same class
        return false;
    Poly other = (Poly) obj; 

    return Arrays.equals(terms, other.terms);  //checking all the array values
}

如果要将 Poly 对象添加到集合中,则还需要实现哈希码方法。

    @Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + Arrays.hashCode(terms);
    return result;
}   

请参考

为什么我需要覆盖 Java 中的 equals 和 hashCode 方法?

使用JPA和Hibernate时equals和hashcode应该如何实现

于 2013-11-11T09:01:59.640 回答
1

看来您需要以下 2 个更改:

  1. 不要使用如下代码比较引用:

    if(this == x){
        q=true;
    }
    

    您需要比较对象的内容 -terms在您的情况下的内容。

  2. 重写equals方法时,最好也重写hashcode方法。

于 2013-11-11T09:02:31.830 回答
0

我的解决方案首先是在术语类中创建一个 equals 方法。然后,您将使用该 equals 方法在多项式类中编写 equals 方法。因此,这里是术语的 equals 方法的代码:

public boolean equals(Term x){
    boolean a= false;
    int expThis = this.getExp();
    int coefThis = this.getCoeff();
    int expX = x.getExp();
    int coefX = x.getCoeff();
    if(expThis==expX && coefThis==coefX){
        a=true;
    }
    return a;
}

我的多项式构造函数已经按降序组织了所有项。如果您有多项式,那么您所要做的就是首先检查这两个多项式的大小是否相同,然后使用 term 类中的 equals 方法来遍历这两个多项式的所有项来比较项。所以这里是多项式的equals方法的代码:

public boolean equals(Object obj) {
    boolean w=false;
    Poly other = (Poly) obj;
    int L1 = other.terms.length;
    int L2 = this.terms.length;
    if(L1==L2){
        for(int q=0; q<L1; q++){
            Term a=other.terms[q];
            Term b=this.terms[q];
            if(a.equals(b)==true){
                w=true;
            }
            else{
                w=false;
                break;
            }
        }
    }
    return w;
}
于 2013-11-22T06:43:10.783 回答