0

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.

1
  • What type does your mReadRowIds contain? Commented Oct 6, 2011 at 20:50

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Superb , I never knew that - learn something every day. Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.