简体   繁体   English

Android ArrayList无法预测的行为

[英]Android ArrayList unpredictable behavior

I am experiencing a strange issue with ArrayList on Android Android上的ArrayList遇到了一个奇怪的问题

If I do this 如果我这样做

        for(int kk=0;kk<mReadRowIds.size();kk++)
        {
            if(mRealRowId==mReadRowIds.get(kk))
            {
                if(kk<mRowNumTimes.size())
                {
                    mArrayNumberPortions.add(mRowNumTimes.get(kk));
                    bFoundIt=true;
                    break;
                }
                else
                {
                    break;
                }
            }
        }

The item is not found, but if I do this 找不到该项目,但如果我这样做

        int readrowidforcmp;
        for(int kk=0;kk<mReadRowIds.size();kk++)
        {
            readrowidforcmp = mReadRowIds.get(kk);
            if(mRealRowId==readrowidforcmp)
            {
                if(kk<mRowNumTimes.size())
                {
                    mArrayNumberPortions.add(mRowNumTimes.get(kk));
                    bFoundIt=true;
                    break;
                }
                else
                {
                    break;
                }
            }
        }

The item is found , can someone explain what the difference between these is to me as I have not got a clue. 该项目被发现,有人可以解释这些是什么区别对我来说,因为我没有线索。 NOTE: Array has to be over 200 items for it to go wrong. 注意:阵列必须超过200个项目才能出错。

It looks like maybe when you call the ArrayList's get(index) method, it's returning a generic object. 看起来可能在调用ArrayList的get(index)方法时,它返回一个通用对象。 In the first example, you're comparing an integer to that generic object, but in the second you're casting the generic object to an integer (by assignment) and then comparing them. 在第一个示例中,您将整数与该泛型对象进行比较,但在第二个示例中,您将通用对象转换为整数(通过赋值),然后比较它们。

It looks like a typical auto-boxing issue. 它看起来像一个典型的自动拳击问题。 In your first solution, you wrote "mRealRowId==mReadRowIds.get(kk)". 在您的第一个解决方案中,您编写了“mRealRowId == mReadRowIds.get(kk)”。 The value in the ArrayList is returned as an Integer and compared to an int auto-cast to an Integer. ArrayList中的值作为Integer返回,并与int自动转换为Integer进行比较。 By comparing the values with == you are performing an identity comparison. 通过将值与==进行比较,您正在执行身份比较。 The trick is that there is a cache of Integer values between -128 and 127, which is why your code starts breaking around 200. 诀窍是在-128和127之间有一个Integer值的缓存,这就是为什么你的代码开始突破200左右的原因。

A simple solution would be to make sure you use only ints and not Integers like in your second solution. 一个简单的解决方案是确保您只使用整数而不是像第二个解决方案中那样使用整数。

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

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