To use recursion with a mix of global variables and parameters is a call to disasters... To mix recursion and iteration is a call to disasters. To make different recursion calls at different syntaxic levels (once in an outer loop and once in an inner loop) is a call to disasters...
Not exiting a loop once a match has been found is generaly a bug (here your '12' is matched twice because it is present twice in the first list. Apparently this is not what you wanted, but anyone else reading your code would be hard pressed to know whether it is intended or not since you didn't comment your method with what it is supposed to do).
Since I Don't see current2 defined in your method, I gather it is a global variable (bad practice in general).
Your method starts a while loop to match each of the remaining object in the second list but it also makes a recursive call to also match the remaining objects in the second list minus the one just matched. This is incorrect, you iterate through a while loop (or similar) OR you make recursive calls. In your case, a second problem is the fact that your index current2 will be modified within the recursive call. When the deepest recursive calls returns, the code will resume to where the previous recursive call was made. When the previous recursive call was made at the end of the wile loop (no match found), the while loop will exit and you'll go back to the next previous place were a recursive call was made but when the previous recursive call was made within the inner loop, that loop will continue before the while loop is exited and this is where you see your strange results.
Bad coding conventions leads to code that is hard to understand and debug.
As a general practice, you should avoid using global variable when possible, definetly avoid mixing iteration and recursion, avoid recursion when possible.
if you replace
if(numberInFirstList == numberInSecondList)
{
numberContained++;
current2++;
searchList(first, second);
}
by
if(numberInFirstList == numberInSecondList)
{
numberContained++;
break;
}
It will work a lot better but it will still be poor programming:
-Code hard to understand
-Unnecessary recursion (leading to unnecessary complexity, unnecessary memory use as well as time lost in the useless calls)
-No javacode comments
Remove the other recursive call below as well and it will work even better though it will still be rather poor programming ( use of a global variable, no comments).
A proper name for the thread would be problem with mixing recursion and iteration
