android for循环使用string []数组

时间:2017-09-05 08:24:31

标签: android for-loop

我可以像这样strings来制作个人string [] array,例如:

//first, make stringArray1 the same size as arrayList1
stringArray1 = new String[arrayList1.size()];

//stringArray1 will contain all the values in arrayList1
stringArray1 = arraylist1.toArray(stringArray1);

//for each value in stringArray1 make it into an individual string,
//called string1
            for(String string1: stringArray1 )

            {
                System.out.println("string1 is " + string1);

             }

你能告诉我如何将string [] array的另一个字符串转换放到同一个for循环中吗? arrayList1arrayList2的大小完全相同。我以为我可以使用&&,但没有快乐。我得到了'Expression expected'。或者我需要有两个不同的for循环? 这就是我所拥有的:

//first, make stringArray1 the same size as arrayList1
stringArray1 = new String[arrayList1.size()];

//second, make stringArray2 the same size as arrayList2
stringArray2 = new String[arrayList2.size()];

//stringArray1 will contain all the values in arrayList1
stringArray1 = arraylist1.toArray(stringArray1);

//stringArray2 will contain all the values in arrayList2
stringArray2 = arraylist2.toArray(stringArray2);

//for each value in stringArray1 make it into an individual string,
//called string1. Do likewise for string2
            for(String string1: stringArray1 && String string2: stringArray2)

            {
                System.out.println("string1 is " + string1);
                System.out.println("string2 is " + string2);

             }

2 个答案:

答案 0 :(得分:3)

您不能使用增强的for循环(foreach循环)同时迭代两个数组。这是因为这样的foreach循环在内部使用Iterator实例迭代元素。

您有几种选择:

  • 使用简单的for循环:

    for (int i = 0; i < arr1.length; i++) {
        System.out.println(arr1[i]);
        System.out.println(arr2[i]);
    }
    

    当然,您必须保证数组的大小相同,否则会发出ArrayIndexOutOfBoundsException

    要静默停止,如果其中一个阵列用尽,您可以使用:

    Iterator<T> it1 = arr1.iterator();
    Iterator<U> it2 = arr2.iterator();
    while (it1.hasNext() && it2.hasNext()) {
        // Do something with it1.next()
        // Do something with it2.next()
    }
    
  • 您还可以更改生成两个ArrayList的代码,并确保它返回一个列表,其中的封装对象包含第一个数组中的元素和第二个数组中相应的一个。

答案 1 :(得分:2)

如果它们具有相同的大小,您可以执行以下操作:

for ( i=0; i<arrayList1.size();i++){
   System.out.println("string1 is " + arrayList1[i]);
   System.out.println("strin2 is " + arrayList2[i]);
}

但使用arrayList1.size()并不是我想的最佳方式