There are 3 string arrays of different lengths. How to iterate through all 3 arrays after 1 cycle?

  • 2
    make a for loop, where the number of passes will be equal to the length of the largest array ...... take the elements and see if the iteration is more than the length of the other two short ones, then skip them .... - Alex Shimansky

2 answers 2

String[] a = new String[10]; String[] b = new String[20]; String[] c = new String[30]; for (int i = 0; i < Math.max(a.length, Math.max(b.length, c.length)); i++) { if(i < a.length) { // опСрация массивом a } if(i < b.length) { // опСрация массивом b } if(i < c.length) { // опСрация массивом c } } 
  • one
    instead of max you can simply write i < a.length || i < b.length || i < c.length i < a.length || i < b.length || i < c.length i < a.length || i < b.length || i < c.length is likely to run faster. Well, either calculate the maximum once before the cycle, and not count at each iteration. - Alex Chermenin
  • @AlexChermenin who knows what array operations will be performed in the body of the loop? For example, if a certain condition is met, the following code can be executed: a = new String(a.length*2); Of course, if this is excluded, then it is better to calculate the maximum value before the cycle or do as you wrote. - GreyGoblin
 String arr1 = new String[]{"a"}; String arr2 = new String[]{"a", "b"}; String arr3 = new String[]{"a", "b", "c"}; for(int i = 0; i < arr1.length + arr2.length + arr3.length; i++) { String arr; int indexOfArr; if(i < arr1.length) { arr = arr1; indexOfArr = i; } else if (i < arr1.length + arr2.length) { arr = arr2; indexOfArr = i - arr1.length; } else { arr = arr3; indexOfArr = i - arr1.length - arr2.length; } System.out.println(arr[indexOfArr]); } 
  • 2
    some complicated muddied) - Alexey Shimansky
  • @ Alexey Shimansky, it's just the first thing that came to mind) It seems that it should work and it is relatively flexible - the array index is known) - YuriySPb ♦
  • @Roman, I will not object to edits) - Yuriy SPb ♦