In Solution 2, you're using IntWrapper
to remember values across recursive invocations. Here, IntWrapper
acts like a global value.
If you use local variables such as a primitive integer, you cannot preserve the incremented (i = i + 1
) values across invocations. Therefore, the statement if (i == k) return head;
never becomes true, unless maybe if k = 1.
Most interestingly, you cannot use Integer
because Java wrapper classes are immutable in nature. The moment you do i = i + 1
, a new object is created (LHS) and the old one (RHS) is thrown away/garbage collected.