使用for循环来计算大小或List <string>?

cod*_*e22 0 java

我有一个for循环,我测试列表的大小.

for(int i = 0; i< thumbLinks.size(); 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);



              }
Run Code Online (Sandbox Code Playgroud)

当我每次添加时,你可以看到我要求我3次获得3个网址.因为我不确定我将拥有多少URL.我用i来增加.我想要的正确输出是

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

等等..

但我的代码不这样做......

它每次只为每个网址添加1.我怎样才能解决这个问题 ?

Jon*_*eet 8

编辑:好的,所以听起来你真的只想处理最多三个网址.所以你想要这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

编辑:我假设您想要出于某种原因分批处理三个URL.如果不是这种情况,目前还不清楚是什么你正在尝试做的.

你的代码不清楚 - 你没有i在调用之间递增thumbLinks.get(i)- 但我怀疑你想要的东西如下:

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
}
Run Code Online (Sandbox Code Playgroud)

要么:

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...
}
Run Code Online (Sandbox Code Playgroud)