Chris
Chris

Reputation: 1637

Android ArrayList unpredictable behavior

I am experiencing a strange issue with ArrayList on Android

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.

Upvotes: 0

Views: 94

Answers (2)

Romain Guy
Romain Guy

Reputation: 98501

It looks like a typical auto-boxing issue. In your first solution, you wrote "mRealRowId==mReadRowIds.get(kk)". The value in the ArrayList is returned as an Integer and compared to an int auto-cast to an 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.

A simple solution would be to make sure you use only ints and not Integers like in your second solution.

Upvotes: 1

Mirthquakes
Mirthquakes

Reputation: 343

It looks like maybe when you call the ArrayList's get(index) method, it's returning a generic object. 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.

Upvotes: 1

Related Questions