user3315024
user3315024

Reputation: 57

java arraylist not working in for loop

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

Upvotes: 1

Views: 779

Answers (2)

murielK
murielK

Reputation: 1030

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.

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157487

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++)

Upvotes: 2

Related Questions