Java: Initialize multiple variables in for loop init?

JavaFor Loop

Java Problem Overview


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();
}

Java Solutions


Solution 1 - Java

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

This would be legal (if silly):

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

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

You can limit the scope of additional variables within methods by using a block like this:

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

This ensures that you don't accidentally reuse the variable elsewhere in the method.

Solution 2 - Java

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

Solution 3 - Java

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

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++) {

Solution 4 - Java

> Variables declared in the initialization block must be of same type

we can't initialize the different data types in the for loop as per their design. I'm just putting a small example.

for(int i=0, b=0, c=0, d=0....;/*condition to be applied */;/*increment or other logic*/){
      //Your Code goes here
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick HeinerView Question on Stackoverflow
Solution 1 - JavaMcDowellView Answer on Stackoverflow
Solution 2 - JavaColin HebertView Answer on Stackoverflow
Solution 3 - JavaNikita RybakView Answer on Stackoverflow
Solution 4 - JavaVishnu Prasanth GView Answer on Stackoverflow