Java – Why doesn’t SparseIntArray.equals(Object) work?

Why doesn’t SparseIntArray.equals(Object) work?… here is a solution to the problem.

Why doesn’t SparseIntArray.equals(Object) work?

I’m using SparseIntArray and I’m confused by this behavior :

public static SparseIntArray getArray()
{
    SparseIntArray result = new SparseIntArray();
    result.append(0, 99);
    result.append(1, 988);
    result.append(2, 636);

return result;
}

public static void testArray()
{
    SparseIntArray first = getArray();
    SparseIntArray second = getArray();
    if( first.equals(second) )
    {
        Log.v(TAG,"first "+first.toString()+" == second "+second.toString());           
    }
    else
    {
        Log.v(TAG,"first "+first.toString()+" != second "+second.toString());
    }
}

Output:

11-06 14:53:15.011: V/fileName(6709): first {0=99, 1=988, 2=636} != second {0=99, 1=988, 2=636}

I

know that using == between two objects compares object addresses, which is different in this case, but here I’m using SparseIntArray.equals(Object other) and the expected result is not unexpected.

I’m sure I can come up with my own comparison method, but that sounds a bit silly. What’s the point if we can’t rely on the base class Object.equals(Object other) method?

Can anyone point out any errors?

Solution

I just searched for the code for SparseIntArray. If you mean android.util.SparseIntArray, which does not override equals, which means it uses the default implementation of the Object class, which compares references.

What is the point for having a base class Object.equals(Object other) method if we cant rely on it?

In fact, you can’t rely on the base class Object.equals because it does exactly what you don’t want to do:

public boolean equals(Object obj) 
{
    return (this == obj);
}

It is up to the writer of any class to decide whether to override equals and provide different implementations.

Related Problems and Solutions