简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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