开发者

Using a for loop to count size or List<string>?

开发者 https://www.devze.com 2023-04-06 06:50 出处:网络
I have a for loop in which i test for the size of a list. for(int i = 0; i< thumbLinks.si开发者_运维技巧ze(); i++) {

I have a for loop in which i test for the size of a list.

for(int i = 0; i< thumbLinks.si开发者_运维技巧ze(); i++) {
                        Log.e("URL" + i, thumbLinks.get(i));




                 url0 = thumbLinks.get(i);
                 url1 = thumbLinks.get(i); 

                 //Fix index out of bounds exception
                 url2 = thumbLinks.get(i);



              }

When i is added each time as you can see i am asking for i 3 times to get 3 urls. Since i am unsure about how many URL's i will have. I use i to increase. The correct output i want is for

    url0 = thumbLinks.get(i);// which is support to be equivalent to 1
    url1 = thunkLinks.get(i);//which is suppose to be equivalent to 2

and so on..

But my code doesnt do this...

It just adds 1 each time to each url. How can i fix this ?


EDIT: Okay, so it sounds like you really only want to deal with up to three URLs. So you want something like:

String url0 = thumbLinks.size() > 0 ? thumbLinks.get(0) : null;
String url1 = thumbLinks.size() > 1 ? thumbLinks.get(1) : null;
String url2 = thumbLinks.size() > 2 ? thumbLinks.get(2) : null;

// Use url0, url1 and url2 where any or all of them may be null

EDIT: I'm assuming you want to deal with the URLs in batches of three for some reason. If that's not the case, it's not clear what you are trying to do.

Your code isn't clear - you're not incrementing i between calls to thumbLinks.get(i) - but I suspect you want something like:

if (thumbLinks.size() % 3 != 0) {
   // What do you want to do if it's not a multiple of three?
   throw new IllegalArgumentException(...);
}
for (int i = 0; i < thumbLinks.size(); i += 3) {
    String url0 = thumbLinks.get(i);
    String url1 = thumbLinks.get(i + 1);
    String url2 = thumbLinks.get(i + 2);
    // Use url0, url1 and url2
}

Or:

int i;
for (i = 0; i < thumbLinks.size() - 2; i += 3) {
    String url0 = thumbLinks.get(i);
    String url1 = thumbLinks.get(i + 1);
    String url2 = thumbLinks.get(i + 2);
    // Use url0, url1 and url2
}
for (; i < thumbLinks.size(); i++) {
  // Deal with the trailing URLs here, one at a time...
}


try this

String[] url=new String[thumbLinks.size()];
for(int i = 0; i< thumbLinks.size(); i++) 
{
Log.e("URL" + i, thumbLinks.get(i));
url[i]=thumbLinks.get(i);
}


You have a dynamic variable within your for loop, this is bad code design. You can have a dynamic value in the first section e.g.

 for(x = getsomedymicvalue(); x > 0; x--)
 { .. }

but having one in the second section is dangerous, can cause exceptions to be thrown (if they change during the loop) and should be avoided when possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号