Java / JUnit - 比较两个多项式对象

时间:2012-11-16 00:47:23

标签: java object junit equals polynomial-math

我有一个名为Term的多样化Java类,如下所示

public Term(int c, int e) throws NegativeExponent {
    if (e < 0) throw new NegativeExponent();
    coef = c;
    expo = (coef == 0) ? 1 : e;
}

我在同一个类中也有一个equals方法,如下面的

@Override
public boolean equals(Object obj) {

}

我坚持如何编码如何比较这两个Term对象

在我的JUnit测试文件中,我使用下面的测试来尝试测试equals方法

import static org.junit.Assert.*;

import org.junit.Test;

public class ConEqTest
{
    private int min = Integer.MIN_VALUE;
    private int max = Integer.MAX_VALUE;



@Test
public void eq01() throws TError { assertTrue(new Term(-10,0).equals(new Term(-10,0))); }

@Test
public void eq02() throws TError { assertTrue(new Term(0,0).equals(new Term(0,2))); }

2 个答案:

答案 0 :(得分:5)

有什么问题
@Override
public boolean equals(Object obj) {
    if (! (obj instanceof Term))
        return false;
    Term t = (Term)obj;
    return coef == t.coef && expo == t.expo; 
}

答案 1 :(得分:1)

import static org.junit.Assert.*;
import org.junit.*;
@SuppressWarnings("serial") class NegativeExponentException extends Exception {}
class Term {
    @Override public int hashCode() {
        final int prime=31;
        int result=1;
        result=prime*result+coefficient;
        result=prime*result+exponent;
        return result;
    }
    @Override public boolean equals(Object obj) {
        if(this==obj)
            return true;
        if(obj==null)
            return false;
        if(getClass()!=obj.getClass())
            return false;
        Term other=(Term)obj;
        if(coefficient!=other.coefficient)
            return false;
        if(exponent!=other.exponent)
            return false;
        return true;
    }
    public Term(int c,int e) throws NegativeExponentException {
        if(e<0)
            throw new NegativeExponentException();
        coefficient=c;
        exponent=(coefficient==0)?1:e;
    }
    int coefficient,exponent;
}
public class So13408797TestCase {
    @Test public void eq01() throws Exception {
        assertTrue(new Term(-10,0).equals(new Term(-10,0)));
    }
    @Test public void eq02() throws Exception {
        assertTrue(new Term(0,0).equals(new Term(0,2)));
    }
    private int min=Integer.MIN_VALUE;
    private int max=Integer.MAX_VALUE;
}