我一直認為Java使用傳遞參考,
但是,我看過幾篇博客文章,聲稱不是(博客文章中說Java使用值傳遞),
我不認為我能理解他們的區別,
有什么解釋?
解決方案
Java總是按值傳遞,
不幸的是,我們根本不處理任何物件,而是處理稱為參考 (當然是通過值傳遞)的物件句柄,選擇的術語和語意很容易使許多初學者感到困惑,
它是這樣的:
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
}
在上面的示例中aDog.getName()仍然會回傳"Max",值aDog內main未在功能改變foo與Dog "Fifi"作為物件基準由值來傳遞,如果是通過參考傳遞的,則aDog.getName()inmain將"Fifi"在呼叫之后回傳foo,
同樣地:
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");
}
在上面的示例中,Fifi是呼叫后的狗的名字,foo(aDog)因為該物件的名稱設定在中foo(...),任何操作是foo執行上d是這樣的,對于所有的實際目的,它們被執行的aDog,但它是不是可以改變變數的值aDog本身,
本文首發于java黑洞網,博客園同步更新
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/275319.html
標籤:其他
上一篇:訪問“ for”回圈中的索引?
