Using equals inside a common class

I would like my generic class to EqualTestercall an overridden method of equals(...)its generic parameter, but instead it calls it instead Object.equals. Here is my test code:

import junit.framework.TestCase;

public class EqualityInsideGenerics extends TestCase {

    public static class EqualTester<V> {
        public boolean check(V v1, V v2) {
            return v1.equals(v2);
        }
    }

    public static class K {
        private int i;
        private Object o;

        public K(Object o, int i) {
            this.o = o;
            this.i = i;
        }
        public boolean equals(K k) {
            return ((k.o != null && k.o.equals(o)) || o == null) && (k.i == i);
        }
    };

    public void testEqual() {
        K k1 = new K(null, 0);
        K k2 = new K(null, 0);
        assertTrue(k1.equals(k2));          // This one ok
        EqualTester<K> tester = new EqualTester<K>();
        assertTrue(tester.check(k1, k2));   // This one KO!
    }
}

Could you explain why this does not work, and how can I change the class EqualTester?

Is it because it Kdoes not actually override the Object.equals () method (because the parameter does not have the right type)?

Thank.

+3
source share
3 answers

You need to enter the code public boolean equals(Object k)and then translate to k.

Now you just overload the equals method.

It is also useful to add @Overrideannotation to the method .

.

+7

equals(K k) equals(Object o).

equals(Object o) , .

+4

Thanks Padmarag and Phill!

Solution that works:

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof K)) {
            return false;
        }
        K k = (K)obj;
        return ((k.o != null && k.o.equals(o)) || o == null) && (k.i == i);
    }

Comments are welcome: I started programming in Java just a few days ago ...

+2
source

All Articles