Reputation: 2266
I have a simple question in java. I have this piece of code:
int i1=0;
for(String x: list1)
{
for(String y: list2)
{
if(x == y)
{
log ("Checking "+x+" with "+y+" => found a match!");
list1.remove(i1);
break;
}
else
{
log ("Checking "+x+" with "+y+" => not matching!");
}
}
i1=i1+1;
}
As u can see, i'm declaring "i1" above, but is there a way to declare it in the first for just once and after the finish of that FOR to unset itself?
Hope you understand me.
Upvotes: 0
Views: 139
Reputation: 5456
I'm not a Java expert, but I remember something about not remove objects from a list while you iterate it.
So (even if I'm wrong), you should do something like this:
for(int i1=0;i<list1.size();i1++)
{
String x=list1.get(i1);
for(String y: list2)
{
if(x == y)
{
log ("Checking "+x+" with "+y+" => found a match!");
list1.remove(i1--);
break;
}
else
{
log ("Checking "+x+" with "+y+" => not matching!");
}
}
}
don't forget the --
in the remove!
Upvotes: 0
Reputation: 177
Maybe you can write the code like this:
for(String x = list1.get(0), int i1 = 0; i1 < list1.size();
i1++, x = list1.get(i1) )
{
for(String y: list2)
{
if(x == y)
{
log ("Checking "+x+" with "+y+" => found a match!");
list1.remove(i1);
break;
}
else
{
log ("Checking "+x+" with "+y+" => not matching!");
}
}
}
If I'm wrong please warn me.
Upvotes: 1
Reputation: 8642
No, you can't do that in Java. If you move the declaration inside the for
loop, then the variable will be reassigned to its initial value on every iteration through the loop.
If by "unset" you mean "go out of scope", you probably don't really need to worry about that; there are no performance issues there. If you really want to force the variable to go out of scope at the end of your outer for
loop, you could create an extra block around the whole thing, like this (but you really don't need to do this, it's unnecessary!):
{ // Beginning of block <----------
int i1=0;
for(String x: list1)
{
for(String y: list2)
{
if(x == y)
{
log ("Checking "+x+" with "+y+" => found a match!");
list1.remove(i1);
break;
}
else
{
log ("Checking "+x+" with "+y+" => not matching!");
}
}
i1=i1+1;
}
} // End of block <----------
Upvotes: 1