public static void swap( int first, int second ) { int temp = first ; first = second ; second = temp ; }Let's say we had the following method call to swap():
public static void main( String [] args ) { int x = 3 , y = 5 ; swap( x, y ) ; System.out.println( "x = " + x + " y = " + y ) ; }What prints out? The answer may surprise you.
x = 3 y = 5It didn't swap! Why not?
In the method swap(), we are swapping copies of the original values, instead of the original values. Since local variables and parameter variables disappear after you exit the method, the swapped values also disappear.
So why did the swap work for an ArrayList?
Thus, any modification to the parameter modifies the same balloon as if you had modified it at the argument.
When we passed list, the ArrayList object to the swap() method, we passed a copy of the handle. Thus, the parameter variable held a handle to the same balloon! Any modifications made in the method were really made.
When we exit the method, the parameter box (and its handle) disappear. But the baloon doesn't! The argument still has a handle to the balloon.
When we learn about arrays, we'll be able to swap primitive variables. It won't be very elegant, but it'll work.
The solution then, to swapping, is either to do it in an ArrayList or not to write a special method. Just swap using the code at the beginning of the lesson, and do it "inline" (i.e., write the code without making a method call).