Programming basics - Techniques and Tricks II -

Joe

Thành viên VIP
21/1/13
2,701
1,246
113
Hi

(cont. Programming basics - Techniques and Tricks -)

5) References and Values. It's known that JAVA won't use the Pointer type like in C/C++ and parameters are passed by "Values". Really? No, not really. Objects (i.e. classes) are passed by "references", too. The passed values are the referenced values (JAVA paradigm). What is the difference? The difference is that you can "overwrite" the "passed Reference values" without causing any problem to the originals. BUT: if you manipulate the content of the object you manipulate the original, too. And that is the hidden danger, or better to say: the hard-to-detect bugs.
PHP:
import java.util.*;
public class Test4 {
  public Test4() {
    ArrayList<String> names = new ArrayList<>();
    names.add("Joe");
    names.add("Bill");
    names.add("Ted");
    // see "Newfangled Programming :o)
    System.out.println("List of names BEFORE payThem()");   
    for (String n: names) System.out.println("Name:"+n);
    payThem(names);
    // see "Newfangled Programming :o)
    System.out.println("List of names AFTER payThem()");   
    for (String n: names) System.out.println("Name:"+n);
  }
  private void payThem(List<String> list) {
    if (list.contains("Joe")) {
      System.out.println("Joe is not a member. No pay!");
      list.remove("Joe");
    }
  }
  //
  public static void main(String... A) {
    new Test4();
  }
}
Code:
C:\examples\Test>javac -g:none -d ./classes Test4.java

C:\examples\Test>java Test4
List of names BEFORE payThem()
Name:Joe
Name:Bill
Name:Ted
Joe is not a member. No pay!
List of names AFTER payThem()
Name:Bill
Name:Ted

C:\examples\Test>
The name "Joe" is missing after payThem(). To avoid such unwanted problems you have to clone the original if the object is your object (implements Clonnable) or copy the original if the object is a standard object and pass it to the method.
PHP:
import java.util.*;
public class Test4a {
  public Test4() {
    ...
    // copy the object. Here: names
    payThem(new ArrayList<String>(names));
    ...
  }
  ...
  public static void main(String... A) {
    new Test4a();
  }
}
Code:
C:\examples\Test>javac -g:none -d ./classes Test4a.java

C:\examples\Test>java Test4a
List of names BEFORE payThem()
Name:Joe
Name:Bill
Name:Ted
Joe is not a member. No pay!
List of names AFTER payThem()
Name:Joe
Name:Bill
Name:Ted

C:\examples\Test>
The name "Joe" still exists after payThem().

(will continue)