View Single Post
Old 06-05-2006, 03:22 PM   #2 (permalink)
Belisarius
Java fanboy
 
Belisarius's Avatar
 
Join Date: Aug 2003
Posts: 1,139
Belisarius is on a distinguished road
That's a very good question. In Java, *everything* is pass-by-value (or pass-by-copy). The misconception comes from not understanding exactly what is being passed.

In Java, if you pass a primitive to a method, you pass the value as opposed to the actual reference to the variable. If you pass an Object, you pass the value of the *reference* (as opposed to the actual reference). This is a very confusing point, and regularly confuses programming experts.

Consider this code:

Code:
public class test{

  static public void main(String[] args){
     int a = 99;
     System.out.println(a);
     foo(a);
     System.out.println(a);
  }

   static public void foo(int a){
      System.out.println(a);
      a = 10;
      System.out.println(a);
   }
}
Now, the output would be:
Quote:
99
99
10
99
I trust you understand why.

Now, let's look at this second example:

Code:
public class test{

  static public void main(String[] args){
     String a = "Hello";
     System.out.println(a);
     foo(a);
     System.out.println(a);
  }

   static public void foo(String a){
      System.out.println(a);
      a = "World";
      System.out.println(a);
   }
}
The output would be:

Quote:
Hello
Hello
World
Hello
This is how you expected it to work, yes?

What you did in your example was actually perform operations on the ArrayList. You will find you can modify an object passed to a method to your hearts content, but you cannot modify the reference, because you are only working on a *copy* of the reference, not the *actual* reference.

Consider it this way - I create object "foo". I then pass a copy of the memory reference to a method. That method now knows where "foo" is stored in memory. I can perform all sorts of operations on that object. But when I exit the method, "foo" still references that object. I cannot destroy or manipulate that reference. It retains the changes I made to the *Object*, but doesn't reflect any changes I made to the *reference*.

Go ahead, you'll find that you cannot make that ArrayList you manipulated equal a new ArrayList from within the method. If you set it equal to a new ArrayList, when you exit the method, you'll find that "list" still equals the old ArrayList.
__________________
GitS
Belisarius is offline   Reply With Quote