Is Java “pass-by-reference” or “pass-by-value”?

Is Java “pass-by-reference” or “pass-by-value”?

结果让人有些意外,到底是 引用传递 还是 值传递?

public class DogTest {

public static void main( String[] args ) {
Dog aDog = new Dog(“Max”);
// we pass the object to foo
foo(aDog);
// aDog variable is still pointing to the “Max” dog when foo(…) returns
if (aDog.getName().equals(“Max”)) { System.out.println(“11=”+aDog);} // true, java passes by value
if (aDog.getName().equals(“Fifi”)) { System.out.println(“22=”+aDog);} // false
}

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”);
if (d.getName().equals(“Fifi”)) { System.out.println(“33=”+d); } // true
}
}

class Dog {
String name;
public Dog(String s ){
name =s ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
// TODO Auto-generated method stub
return String.format(” Dog[name=%s]”, name);
}
}

来源: methods – Is Java “pass-by-reference” or “pass-by-value”? – Stack Overflow

好烂啊有点差凑合看看还不错很精彩 (No Ratings Yet)
Loading...
318 views

发表评论

电子邮件地址不会被公开。 必填项已用*标注

跳至工具栏