繁体   English   中英

为什么SparseIntArray.equals(Object)不起作用?

[英]Why is SparseIntArray.equals(Object) not working?

我正在使用SparseIntArray ,我对这种行为感到困惑:

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());
    }
}

输出:

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

我知道在两个对象之间使用==将比较对象地址,在这种情况下是不同的,但在这里我使用的是SparseIntArray.equals(Object other) ,并且预期的结果并不意外。

我相信我可以推出自己的比较方法,但听起来有些愚蠢。 如果我们不能依赖它,那么有一个基类Object.equals(Object other)方法有什么意义呢?

有人能指出任何错误吗?

我刚刚搜索了SparseIntArray的代码。 如果你指的是android.util.SparseIntArray ,它不会覆盖equals ,这意味着它使用Object类的默认实现,它比较引用。

如果我们不能依赖它,那么有一个基类Object.equals(Object other)方法有什么意义呢?

实际上,你不能依赖基类Object.equals,因为它确实是你不想做的事情:

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

由任何类的编写者来决定是否重写equals并给出不同的实现。

@Eran是对的,Object.equals(Object)不会削减它。

我做了一个简单的静态方法来比较两个实例

public static boolean compareSame( SparseIntArray first, SparseIntArray second )
{
    // compare null
    if( first == null )
    {
        return (second == null);
    }
    if( second == null )
    {
        return false;
    }

    // compare count
    int count = first.size();
    if( second.size() != count )
    {
        return false;
    }

    // for each pair
    for( int index = 0; index < count; ++index )
    {
        // compare key
        int key = first.keyAt(index);
        if( key != second.keyAt(index))
        {
            return false;
        }

        // compare value
        int value = first.valueAt(index);
        if( second.valueAt(index) != value)
        {
            return false;
        }
    }       

    return true;
}

我可能最终会得到我自己的SparseIntArray版本并覆盖equals方法,我认为这样更干净。

[编辑]这是实现equals的子类的代码

import android.util.SparseIntArray;

public class SparseIntArrayComparable extends SparseIntArray {
@Override
public boolean equals( Object obj ) {

    if( obj instanceof SparseIntArray ) {
        SparseIntArray other = (SparseIntArray)obj;

        // compare count
        int count = size();
        if( count != other.size() )
            return false;

        // for each pair
        for( int index = 0; index < count; ++index ) {

            if( keyAt(index) != other.keyAt(index))
                return false;

            if( valueAt(index) != other.valueAt(index) )
                return false;
        }       

        return true;
    }
    else
        return false;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM