开发者

Equals(Obj) Testing

开发者 https://www.devze.com 2023-01-27 00:36 出处:网络
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.

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:

  • equals is not defined as a method of SparsePolynomial. Perhaps you've defined it on a superclass ... or an unrelated class.
  • You haven't recompiled all relevant classes after changing some code.

EDIT

  1. It is a good idea to use the @Override annotation to flag that you intend the equals method 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.)
  2. Your change to the Assert method used for testing should make no difference to the result.
  3. The equals method you've shown is clearly bogus. It is just testing the type of the obj parameter, and ignoring its state. As written, it should return true every time you test one SparsePolynomial instance 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));
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消