[英]Is there a difference between initializing a variable using new, followed by assignment and just assignment on initialization?
我正在嘗試學習Java。
我有一個自定義類,它具有以下屬性:
public class Person{
private String name;
}
我在另一堂課,在那里:
public class foo{
private Person guy;
public void setGuy(Person guy){
this.guy = guy;
}
public Person getGuy(){
return guy;
}
void someMethod(){
Person anotherGuy = new Person();
anotherGuy = getGuy();
}
}
當我使用getGuy()
方法時,我很困惑。 我以為這樣做的時候:
Person anotherGuy = new Person();
anotherGuy = getGuy();
我創建一個新對象,該對象具有與guy相同的值。 但是似乎anotherGuy實際上是指向guy的指針。 所以
Person anotherGuy = getGuy();
和上面的兩行,完全一樣嗎? 我很困惑。 另外,我該如何在內存中創建一個全新的對象?
所以
Person anotherGuy = getGuy();
和上面的兩行,完全一樣嗎?
不,其他版本會先創建一個新的Person()對象,然后將其丟棄(這只是浪費內存和處理器周期)。
Person anotherGuy;
這是對Person對象的引用
anotherGuy = new Person();
這將引用設置為新的Person對象
anotherGuy = getGuy();
這會將引用設置為與foo的guy成員相同的引用。
我想“復制”對象,可能需要看看Object.clone()
盡管人們已經討論過/解釋了現有代碼的行為,但是為了執行您想要的操作,請使用Java中的clone
功能,其中Person類將實現Cloneable
接口,該接口將要求您實現clone()
方法。
您的clone()
方法應如下所示:
public Object clone()
{
Person p = new Person();
p.setName(this.name);
// similarly copy any other properties you want
return p;
}
然后調用clone復制您的對象:
Person another = (Person) person.clone();
Java變量只能包含基元和引用。 Person
是對對象的引用。 (您不必像在C ++中那樣使用&
,因為它是唯一的選擇)
當你做
Person anotherGuy = new Person(); // create a new object and assign the reference.
anotherGuy = getGuy(); // change the reference in `anotherGuy` to be the one returned by getGuy();
是的,兩者都做同樣的事情,因為在兩個方法調用之后, anotherGuy == null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.