-1

It may be a dummy question but I could not find an answer to that. Is that possible to pass 2 parameters to an enhanced Java for loop? something like:

List A = [1, 2, 3]
List B = [a, b, c]
for (int i: A ; String a in B) {
  do something
}
abbas
  • 235
  • 1
  • 3
  • 14
  • 2
    No, you can either replace the enhanced for with a normal for and loop over both at the same time or you can have a for loop inside the other one, depending on your use case. – ThexXTURBOXx Jun 07 '20 at 10:41
  • Or [this](https://stackoverflow.com/q/3137944/10871900) – dan1st Jun 07 '20 at 10:49

2 Answers2

0

You can loop through both arrays with a normal for loop and access both with the same index

    int[] A = new int[]{1, 2, 3};
    String[] B = new String[]{"a", "b", "c"};
    for (int i = 0; i < A.length; i++) {
        System.out.println(A[i]);
        System.out.println(B[i]);
    }
0

No you can't pass two variables to same enhanced for loop , to achieve what you need to do use the iterator interface which is fallen under java.util package . By using iterator and it's methods of boolean hasNext() and Object next() you can achieve this.

SOLUTION:

 Iterator iteratorA = A.iterator(); 
 Iterator iteratorB = B.iterator(); 

  while(iteratorA.hasNext() && iteratorB.hasNext()) {
    valueA = iteratorA.next();
    valueB =  iteratorB.next();

    //other logics
  }
Hasindu Dahanayake
  • 1,344
  • 2
  • 14
  • 37