簡體   English   中英

Java / JUnit - 比較兩個多項式對象

[英]Java / JUnit - comparing two polynomial objects

我有一個名為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))); }

怎么了?

@Override
public boolean equals(Object obj) {
    if (! (obj instanceof Term))
        return false;
    Term t = (Term)obj;
    return coef == t.coef && expo == t.expo; 
}
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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM