méthodes - Est le pass-by-reference ou le pass-by-value Java

Mots clés : javamethodsparameter-passingpass-by-referencepass-by-valuejava

meilleur 4 Réponses méthodes - Est le pass-by-reference ou le pass-by-value Java

vote vote

96

public static void main(String[] args) {     Dog aDog = new Dog("Max");     Dog oldDog = aDog;      // we pass the object to foo     foo(aDog);     // aDog variable is still pointing to the "Max" dog when foo(...) returns     aDog.getName().equals("Max"); // true     aDog.getName().equals("Fifi"); // false     aDog == oldDog; // true }  public static void foo(Dog d) {     d.getName().equals("Max"); // true     // change d inside of foo() to point to a new Dog instance "Fifi"     d = new Dog("Fifi");     d.getName().equals("Fifi"); // true } 
public static void main(String[] args) {     Dog aDog = new Dog("Max");     Dog oldDog = aDog;      foo(aDog);     // when foo(...) returns, the name of the dog has been changed to "Fifi"     aDog.getName().equals("Fifi"); // true     // but it is still the same dog:     aDog == oldDog; // true }  public static void foo(Dog d) {     d.getName().equals("Max"); // true     // this changes the name of d to be "Fifi"     d.setName("Fifi"); } 
vote vote

83

Dog myDog; 
Dog myDog = new Dog("Rover"); foo(myDog); 
public void foo(Dog someDog) {     someDog.setName("Max");     // AAA     someDog = new Dog("Fifi");  // BBB     someDog.setName("Rowlf");   // CCC } 
vote vote

73

public class Main {       public static void main(String[] args) {           Foo f = new Foo("f");           changeReference(f); // It won't change the reference!           modifyReference(f); // It will modify the object that the reference variable "f" refers to!      }       public static void changeReference(Foo a) {           Foo b = new Foo("b");           a = b;      }       public static void modifyReference(Foo c) {           c.setAttribute("c");      }  } 
Foo f = new Foo("f"); 
public static void changeReference(Foo a) 
changeReference(f); 
Foo b = new Foo("b"); 
vote vote

61

1. Person person; 2. person = new Person("Tom"); 3. changeName(person); 4. 5. //I didn't use Person person below as an argument to be nice 6. static void changeName(Person anotherReferenceToTheSamePersonObject) { 7.     anotherReferenceToTheSamePersonObject.setName("Jerry"); 8. } 

Questions similaires