Java: initialize multiple variables for init loop?

I want to have two loop variables of different types. Is there any way to make this work?

@Override public T get(int index) throws IndexOutOfBoundsException { // syntax error on first 'int' for (Node<T> current = first, int currentIndex; current != null; current = current.next, currentIndex++) { if (currentIndex == index) { return current.datum; } } throw new IndexOutOfBoundsException(); } 
+69
java for-loop
Aug 22 '10 at 18:55
source share
3 answers

initialization of the for statement follows the rules of local variable declarations .

This will be legal (if silly):

 for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) { // something } 

But trying to declare different types of Node and int as you want is not legal for local variable declarations.

You can limit the scope of additional variables in methods using this block:

 { int n = 0; for (Object o = new Object();/* expr */;/* expr */) { // do something } } 

This ensures that you do not accidentally reuse the variable elsewhere in the method.

+82
Aug 22 '10 at 19:58
source share

You won’t like it. Either you use multiple variables of the same for(Object var1 = null, var2 = null; ...) type for(Object var1 = null, var2 = null; ...) , or you extract another variable and declare it before the for loop.

+14
Aug 22 '10 at 19:00
source share

Just move the variable declarations ( Node<T> current , int currentIndex ) outside the loop, and it should work. Something like that

 int currentIndex; Node<T> current; for (current = first; current != null; current = current.next, currentIndex++) { 

or maybe even

 int currentIndex; for (Node<T> current = first; current != null; current = current.next, currentIndex++) { 
+6
Aug 22 '10 at 18:59
source share



All Articles