1

am new to java and facing problem with arraylist , i do not know whats wrong with my "for loop" am unable to exit it , producing error it end

        ArrayList<String> r2 = new ArrayList<String>();
        for(int i=0; i<= idx.length; i++) {
            ArrayList<String> r = db.Fetch(idx[i],exta); 
            if(r.size() != 0) {  
                for (String s : r) {
                    r2.add(s);
                    Log.d("test","ID "+idx[i]+ " :" + s);
                }
            }
        }

When i run it i get correct values printed on Log.d but the loop not exit it end so help

3
  • What is idx? Also, the inner for-loop seems to be correct. Commented Feb 24, 2014 at 14:14
  • 1
    can you post your complete code? to be clearer Commented Feb 24, 2014 at 14:15
  • 1
    Your error is in the 2nd line. Try following code for(int i=0; i<idx.length; i++). Since the for-loop starts at 0, you can't access an element at location X if the size of the ArrayList. The way your code is build up right now, you'll run into an ArrayOutOfBoundsException... Commented Feb 24, 2014 at 14:16

2 Answers 2

2
for(int i=0; i<= idx.length; i++)

the indexes of you ArrayList go from 0 to idx.lenght -1 . Looping on the idx.lenght index will cause an ArrayIndexOutBoundExeception. Change it in

   for(int i=0; i <  idx.length; i++)
Sign up to request clarification or add additional context in comments.

Comments

0
ArrayList<String> r2 = new ArrayList<String>();
for(int i=0; i< idx.length; i++)
{
    ArrayList<String> r = db.Fetch(idx[i],exta); 

    if(r.size() != 0) {  
        for (String s : r)
        {
            r2.add(s);
            Log.d("test","ID "+idx[i]+ " :" + s);
        }
    }
}

This should work now. You start i at 0 so when i will be equal to idx.length your array at this position dos not exist.

Comments

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.