Equals(Obj) Testing
I'm testing to see if the the two objects are equal yet it returns false. Could someone explain to me why this is happening? Thanks.
public boolean equals(Object obj) {
if(obj instanceof SparsePolynomial)
{
return true;
}
return false;
}
@Test
public void testEqualsObj()
{
ArrayList<Integer> k = new ArrayList<Integer>();
k.add(1);
k.add(3);
SparsePolynomial d = new SparsePolynomial(k);
ArrayList<Integer> k2 = new ArrayList<Integer>();
k.add(1);
k.add(3);
SparsePolynomial d2 = new SparsePolynomial(k2);
Assert.assertTrue(d.equals(d2));
开发者_运维技巧}
There is insufficient information to be sure, but I suspect that either:
equalsis not defined as a method ofSparsePolynomial. Perhaps you've defined it on a superclass ... or an unrelated class.- You haven't recompiled all relevant classes after changing some code.
EDIT
- It is a good idea to use the
@Overrideannotation to flag that you intend theequalsmethod to override (or implement) a method defined in a superclass or interface. (It won't make any difference here, but it would tell you if you had made a mistake with the method signatures.) - Your change to the Assert method used for testing should make no difference to the result.
- The
equalsmethod you've shown is clearly bogus. It is just testing the type of theobjparameter, and ignoring its state. As written, it should returntrueevery time you test oneSparsePolynomialinstance against another.
Try instead Assert.assertTrue(d.equals(d2));
I've tried your code and the test passes.
You can find exact test case I've used here:
public class SparsePolynomialTest {
public static class SparsePolynomial {
private List<Integer> list;
public SparsePolynomial(List<Integer> list) {
this.list = list;
}
public boolean equals(Object obj) {
if (obj instanceof SparsePolynomial) {
return true;
}
return false;
}
}
@Test
public void testEqualsSparse() {
ArrayList<Integer> k = new ArrayList<Integer>();
k.add(1);
k.add(3);
SparsePolynomial d = new SparsePolynomial(k);
ArrayList<Integer> k2 = new ArrayList<Integer>();
k2.add(1);
k2.add(3);
SparsePolynomial d2 = new SparsePolynomial(k2);
Assert.assertEquals(true, d.equals(d2));
}
}
加载中,请稍侯......
精彩评论